The question is how to make a simple java swing application.
I need to have the first window, by clicking on the button, the second window should open, and the first should be closed.

The current code is:

public class SimpleGUI extends JFrame{ private JFrame frame = new JFrame(); public SimpleGUI(){ super("Example"); frame.setBounds(100,100,250,100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container container = this.getContentPane(); container.setLayout(new GridLayout(3,2,2,2)); JLabel label = new JLabel("Label"); container.add(label); JButton button = new JButton("YES"); container.add(button); JButton button2 = new JButton("NO"); container.add(button2); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.setVisible(false); JFrame frame2 = new JFrame(); frame2.setBounds(100,100,250,100); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setVisible(true); } }); } } 

like frame.setVisible(false); should close the first window, but nothing happens.

Here is the code from the main method

 public class Runner { public static void main(String[] args) { SimpleGUI app = new SimpleGUI(); app.setVisible(true); } } 
  • So you first open the first window. And then close what is not visible - Chubatiy
  • It opens the first window, with buttons, after pressing the button, the second window opens, but the first does not close - D.Mark

1 answer 1

It is not at all clear why you create a field of type Frame in the main window and assign parameters to it, and then call setVisible(false) on it, it is not displayed anyway. I propose to remove it, then your code with a few changes will be working.

 public class MyWindow extends JFrame { public MyWindow() { setTitle("first frame"); setBounds(100, 100, 250, 100); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container container = this.getContentPane(); container.setLayout(new GridLayout(3, 2, 2, 2)); JLabel label = new JLabel("Label"); container.add(label); JButton button = new JButton("YES"); container.add(button); JButton button2 = new JButton("NO"); container.add(button2); button.addActionListener(e -> { setVisible(false); JFrame frame = new JFrame(); frame.setTitle("second frame") frame.setBounds(100, 100, 250, 100); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); }); } public static void main(String[] args) { MyWindow myWindow = new MyWindow(); myWindow.setVisible(true); }} 
  • Thank you very much! - D.Mark