【问题标题】:new panel but same window?新面板但相同的窗口?
【发布时间】:2018-01-09 17:23:14
【问题描述】:

我目前正在构建一个 GUI,可以让人们选择购买/出售(基本上是发送/接收)。我想要实现的是让用户点击买入/卖出,当他们点击该按钮时,它会显示新信息。

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

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() 函数中看到的那样,我试图让它在同一个窗口内执行。

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

【问题讨论】:

    标签: java intellij-idea panels


    【解决方案1】:

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

    为了方便实现,你的 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 应该是您要在框架中设置的面板...

    【讨论】:

    • 我在 btnpurchase 监听器中添加了您的行...... frame.setContentPane(new GuiTest().panelPurchase);出现错误 - contentPane 不能设置为 null。我还为它创建了一个表单并创建了一个 JPanel 并将其命名为 panelPurchase @BluEOS
    • 你必须实例化你的对象.... private JButton btnpurchase=new JButton("Hello from Purchase Button");
    • btnpurchase 已经在公共类下实例化了。我不能把它放在动作监听器中,因为实例不能是公共的或私有的。
    • 请查看此图片imgur.com/PLgzVff 如果我没有组件声明,则会显示为组件无法解析。当我运行程序时,它说它卡在第 40 行,说它不能为空
    • 我的错,我忘记了 IntelliJ 隐藏了所有有趣的东西!我能给你的最好建议是忘记“设计师”工具。 Juste 编写纯 Java,它将解决您的所有问题。查看小而完整的示例,例如docs.oracle.com/javase/tutorial/uiswing/components/button.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多