Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling and disabling button based on whether frame is open

I have a button that opens up a frame. Is there a way to enable/disable a button depending on whether the frame is open?

Let's say, if the frame is open, I would like the button to be button.enabled(false). But as soon as the frame is closed, I would like to change it to button.enabled(true).

In my actionPerformed method of the button I do this

JFrame testFrame = new JFrame();
testFrame.setSize(100,100);
testFrame.setVisible(true);

However, I don't want to open up more than one of these frames at a time. So while the frame that is created by the click of the button is open, I want the button disabled until the frame is closed. (Even if the frame is not visible, I still don't want to allow another one to be opened)

like image 486
WilliamShatner Avatar asked May 24 '26 04:05

WilliamShatner


2 Answers

You probably shouldn't be opening a dependent window as a JFrame from another GUI. Likely you're much better off opening a dialog such as a modal or non-modal JDialog or JOptionPane. Please understand that either of these two critters can hold very complex GUI's. For instance, please have a look here for an example: how-do-you-return-a-value-from-a-java-swing-window-closes-from-a-button

Also if your dialog variable is a field of your class, then it is created only once and you can't have two of these windows displayed even if the button to display it is pressed more than once.

Your code could look something like...

// testDialog is a JDialog field. and this line is called in 
// the class constructor.
JDialog testDialog = new JDialog(theCurrentJFrame, "Dialog Title", false); // true 
                                                                    // if modal

// this line is called in the button's ActionListener.
testDialog.pack(); // Never set the size of your GUI's. 
                   // Let the layout managers do this for you.
testDialog.setVisible(true);
like image 74
Hovercraft Full Of Eels Avatar answered May 25 '26 19:05

Hovercraft Full Of Eels


Add an onClose listener that sets the button to enabled when the user(or program) closes the frame. Likewise add a line to disable the button in the call that opens the frame in the first place.

like image 31
Thomas Avatar answered May 25 '26 18:05

Thomas