Reputation: 2237
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)?
Upvotes: 3
Views: 5623
Reputation: 7706
Build the Form2 ahead of time and use setVisible(true) to show it and and setVisible(false) to hide it. Here as an example:
if(e.getSource()==btn1){
btn1.setVisible(false); // not really needed if you disable form1 on btn1 press
form2.setVisible(true); // show form2
form1.setVisible(false); // hide form1
}
Upvotes: 2
Reputation: 81684
This seems like a fine way, but yes, there are other ways too. Your class could keep a reference to the child JFrame
as a member variable. The button could check if that member is null
or disposed, and if so, create a new one; but otherwise it could just bring the existing child to the front.
Upvotes: 6
Reputation: 168825
Use a modal dialog instead. See How to Make Dialogs for more details.
A Dialog can be modal. When a modal Dialog is visible, it blocks user input to all other windows in the program.
JOptionPane
createsJDialogs
that are modal. To create a non-modal Dialog, you must use theJDialog
class directly.
Upvotes: 7