Toggle the button on and off based on whether a frame is open

I have a button that opens a frame. Is there a way to enable / disable the 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 once the frame is closed, I would like to change it to button.enabled(true)

.

In my actionPerformed method of the button I am doing this

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

      

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

+3


source to share


3 answers


You probably shouldn't open the dependent window as a JFrame from another GUI. You are probably much better off opening a dialog like a modal or modeless JDialog or a JOptionPane. Please understand that either of these two critters can contain very complex graphical interfaces. For example, please see an example here: 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, it is created only once, and you cannot display two of these windows, even if the button to display it is clicked more than once.



Your code might look something like this ...

// 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 ActionListener.
testDialog.pack(); // Never set the size of your GUI's. 
                   // Let the layout managers do this for you.
testDialog.setVisible(true);

      

+3


source


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



+3


source


If your intent is for the button to create only one window, then I would suggest turning off the enable of the button instead, you must specify a single JFrame, so there is a class variable somewhere in your code:

JFrame myFrame = null;

      

Then the button code should be:

If (myFrame == null) {
    myframe = new JFrame();
    //set up the frame etc
    myFrame.setVisible();
} else {
    myFrame.setVisible();
    //code to bring focus to myFrame
}

      

To be honest, I can't think of a better way to draw attention to a window, but here are some links:

How do I bring the window to the front? http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2006-06/msg00152.html

+3


source







All Articles