I have a main JFrame. There is a button inside the frame. When I click the button, it opens the child frame.
But I only want only 1 child frame is opend at any time, (instead whenever i click the button again , it give me the second child frame, and so on…).
So, I added actionListener to the button, to make it disable when the child frame is openning, and add windowListener to the child frame, so that When i click the close button on the top-right corner, it make the button (on the main frame) able.
Here is my code :
import java.awt.Button;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Form1 extends JFrame implements ActionListener{
JButton btn1=new JButton("help");
public Form1() {
super("Form 1");
this.add(btn1);
setSize(200, 200);
btn1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn1){
btn1.setEnabled(false);
final Form2 x= new Form2();
x.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
x.dispose();
btn1.setEnabled(true);
}
});
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
@Override
public void run() {
new Form1();
}
});
}
}
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Form2 extends JFrame {
JLabel lbl1=new JLabel("đang mở form 2 - trợ giúp");
public Form2() {
super();
add(lbl1);
setVisible(true);
setSize(200, 200);
}
}
So, my question is : Is there other way that I could let only one child frame opened (it means that when that child frame is opening, clicking the button in the main frame do nothing unless the that child frame is closed)?
This seems like a fine way, but yes, there are other ways too. Your class could keep a reference to the child
JFrameas a member variable. The button could check if that member isnullor disposed, and if so, create a new one; but otherwise it could just bring the existing child to the front.