Junaid
Junaid

Reputation: 63

How do I set JFrame's visibility to False after button click on IntelliJ?

UI2 is a JFrame that I have modelled using IntelliJ's Swing UI Designer --> GUI form. I have added a button in this frame that will open another frame when it is clicked. I want to set the current frame's visibility to false after the button is clicked and before the other frame is opened. And I can't access the current frame in the button's action listener method. Any tips? Sorry if the question is unclear.

 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);
    }}

Upvotes: 0

Views: 885

Answers (1)

matt
matt

Reputation: 12347

One solution is to just add a field to your class.

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

Then in your main method. Change the set content pane to.

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);
}

Now everything in UI2 can access the showingFrame.

Upvotes: 1

Related Questions