问题
i can open a form or another forms when button is clicked in netbeans. such as the following code
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
frame1 fr = new frame1();
desktop.add(fr);
fr.setVisible(true);}
but i want to control that is current form is open or close? if current form is open then when i click same button not open current form again until its closed the same form. how can i make it? there is some methods like isclosed(), isDisplayable(), but i dont khow how can i use these? please give me advice.
回答1:
You could use Boolean variables to determine whether or not the allowance of opening a frame.
example:
//declaring the boolean in a class in which both frames can access
public final class Allow {
private Allow(){}
public static Boolean allow_ = true;
}
In your main frame code where you open the secondary frame you can do this
if(Allow.allow_ == true) {
Allow.allow_ = false;
secondFrame sFrame_ = new secondFrame();
sFrame_.setVisible(true);
} else {
//alert the user that the frame is already open
//I recommend a JOptionPane such as this
JOptionPane.showMessageDialog(null, "This window is already open");
}
So now the second frame is open, and now it will only let you open it if allow_ is true.
Now when you close the second frame you do this:
Allow.allow_ = true;
secondFrame.this.setVisible(false);
secondFrame.this.dispose();
Now the second frame is closed, and will now be allowed to be opened once again.
来源:https://stackoverflow.com/questions/8777547/how-can-i-check-that-a-frame-is-open-or-not-in-java