Basically, what I wanted to do is to close a JFrame
with a button in the same class. I have 2 classes Class1
and Class2
. When I click on the button "Add data" in Class1
, it will open Class2
(sort of like a dialog box) and I want to close Class2
when I click on the "Done" button.
-------------------------------Class1-------------------------------
public class Class1 extends JFrame{
private JPanel contentPane;
public Class1(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 355, 251);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setForeground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Add labels and other relevant content here
JButton addData = new JButton("Add Data");
addData.setBounds(32, 135, 130, 23);
contentPane.add(addData);
addData.addActionListener(new addDataActionListener());
}
class addDataActionListener implements ActionListener{
public void actionPerformed(ActionEvent arg5) {
Class2 co = new Class2();
co.setVisible(true);
//opening the Class2 JFrame
}
}
}
-------------------------------Class2-------------------------------
public class Class2 extends JFrame {
private JPanel contentPane;
public Class2(){
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 415, 238);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Add labels and other relevant content here
JButton done = new JButton("Done");
done.setBounds(206, 164, 89, 23);
contentPane.add(done);
done.addActionListener(new doneActionListener());
}
class doneActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
//add stuff that needs to be done
Class2 co2 = new Class2();
co2.setVisible(false);
co2.dispose();
}
However, when I click on the "Done" button, it performs all the other actions, but does not close the frame in Class2. It would be appreciated if somebody can let me know how it's done.
Ps. I'm new to Java (started about 4 months ago). Sorry if I'm not being clear enough. Thanks in advance :)