首页 > 解决方案 > 单击 IntelliJ 按钮后,如何将 JFrame 的可见性设置为 False?

问题描述

UI2 是我使用 IntelliJ 的 Swing UI Designer --> GUI 表单建模的 JFrame。我在此框架中添加了一个按钮,单击该按钮将打开另一个框架。我想在单击按钮之后和打开另一个框架之前将当前框架的可见性设置为 false。而且我无法在按钮的动作侦听器方法中访问当前帧。有小费吗?抱歉,如果问题不清楚。

 public class UI2 {
        JPanel rootPanel;
        JPanel northPanel;
        JPanel westPanel;
        JPanel southPanel;
        JButton button1;
        JLabel header;
        JTextField textField1;



   public UI2() {
        button1.addActionListener(new ActionListener()  {
            @Override
            public void actionPerformed(ActionEvent e) {

                JFrame frame2 = new JFrame();
                frame2.setContentPane(new next_f().Panel1);
                frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame2.pack();
                frame2.setVisible(true);

            }
        });
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("UI");
        frame.setContentPane(new UI2().rootPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }}

标签: javaswingjframe

解决方案


一种解决方案是向您的班级添加一个字段。

public class UI2 {
    JPanel rootPanel;
    JPanel northPanel;
    JPanel westPanel;
    JPanel southPanel;
    JButton button1;
    JLabel header;
    JTextField textField1;
    JFrame showingFrame;
    ...
    }

然后在你的主要方法中。将设置内容窗格更改为。

public static void main(String[] args) {
    JFrame frame = new JFrame("UI");
    UI2 ui2 = new UI2();
    ui2.showingFrame = frame;
    frame.setContentPane(ui2.rootPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

现在 UI2 中的所有内容都可以访问showingFrame。


推荐阅读