新面板但相同 window?

new panel but same window?

我目前正在构建一个 GUI,让人们可以选择 buy/sell(基本上是 send/receive)。我想要实现的是让用户点击 buy/sell,当他们点击那个按钮时,它会显示新信息。

例如。用户点击购买,它会将他们带到一个带有新标签新按钮等的新面板。我不想要新的 window 但要替换当前的 window。

public class GuiTest {
    private JButton btnpurchase;
    private JPanel panelMain;
    private JButton btnrefund;

    public GuiTest() {
        btnpurchase.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null,"Buying stuff.");
                purchasecontent();
            }
        });
        btnrefund.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null,"Refunding stuff.");
                refundcontent();
            }
        });
    }
    public static void purchasecontent(){
        //enter the amount of the purchase

    }
    public static void refundcontent(){

    }
    public static void main(String[] args){
        JFrame frame = new JFrame("GuiTest");
        frame.setContentPane(new GuiTest().panelMain);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setSize(480,320);
        frame.setVisible(true);
    }
}

正如您在 purchasecontent() 函数中看到的那样,我试图让它执行,但在同一个 window.

我目前正在使用 IntelliJ IDE 并且正在使用表单设计器。

首先,您必须避免从侦听器调用静态方法 :) 这是一种不好的做法。

为了方便实现,你的GuiTest必须继承自JPanel,把它当作你的主面板。

要替换内容,获取框架使用:

JFrame frame = (JFrame) SwingUtilities.getRoot(component);

并设置新的内容,例如:

 btnrefund.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
              JFrame frame = (JFrame) SwingUtilities.getRoot(component);
              frame.setContentPane(new RefundPanel());
            }
        });

RefundPanel 应该是您要在框架中设置的面板...