Closing a JFrame via JButton while opening a new JFrame

618 views Asked by At

I know this has been asked thousands of times, but I have never found an answer that works for me. I'm using Java IDE for Java Developers (Eclipse Kepler).

I need to have a JButton which by clicking it, it will close the JFrame that the button is on, and opens a new one that exists in a different class. I have this:

        JButton button = new JButton("Click Me!");
        add(button);
        

        button.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) {

            }
        }); 
        
    }

I have no idea what to put after the actionPerformed. And frame.dispose(); does not work for me.

I'm asking, how do I close the JFrame with a JButton, and by clicking the same button it also opens a new class's JFrame?

1

There are 1 answers

1
Edwin Torres On BEST ANSWER

Here's an example that may help:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class MyFrame extends JFrame {

    public MyFrame() {

        setLayout(new BorderLayout());
        getContentPane().setPreferredSize(new Dimension(400, 250));

        JButton btn = new JButton("Click Me");
        btn.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) { 
                setVisible(false);

                JFrame frame2 = new JFrame();
                frame2.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame2.setLocation(300, 150);
                frame2.add(new JLabel("This is frame2."));
                frame2.setVisible(true);
                frame2.setSize(200, 200);

            } 
        } );
        add(btn,BorderLayout.SOUTH);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MyFrame frame = new MyFrame();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.add(new JLabel("This is frame1."), BorderLayout.NORTH);
                frame.setVisible(true);
            }
        });
    }
}