Reputation:
I am using to different classes: one holding a main JFrame with a button, and one holding a new JFrame that is called upon at a button press.
if( event.getSource() == noteBtn ) { MiniPad.pad(); return;}
(MiniPad.pad() references the class and pad() method on the new JFrame)
When I removeAll() on the JPanel that hosts the button, and then revalidate() and repaint(), the button opens the JFrame multiple times, which isn't what I want it to do at all.
Is there a way to tell the MiniPad class that you can't have more than one copy of the JFrame open at any one time? I extend the JFrame by the way, in case that's any help.
Upvotes: 1
Views: 3743
Reputation: 316
Edit: Everything below is valid programming knowledge, but you might also want to consider having MiniPad
extend the JDialog
class instead. I haven't used it before, but its implementation looks a lot like JFrame
. You might not actually have to change much in your MiniPad
class. The documentation is here: http://docs.oracle.com/javase/7/docs/api/javax/swing/JDialog.html
If you're wondering why, check out Andrew Thompson's post here.
--
From what I understood of your question, MiniPad
extends JFrame
, and the pad()
method creates a new instance of the MiniPad
class. The simplest solution would be to turn the MiniPad
class (at least through the pad()
method) into a singleton. A singleton is a type of class where only one instance (or object) can exist at any given time. By calling a static method (in this case pad()
) you check to see if an instance of the object already exists; if it does, simply use that existing object:
public class MiniPad extends JFrame {
//whatever code you have
private static MiniPad padInstance = null; //the singleton instance of your MiniPad
public static MiniPad pad() {
if(padInstance == null)
padInstance = new MiniPad();
//If you want to reset the object every time you call the method for whatever reason, do it here
pad.setVisible(true); // I believe this is all you want to do
}
}
This should do what you want. By calling the pad()
method, only one MiniPad
will ever show up.
However, if I read your question wrong, let me know and I will revise my answer.
Info on singletons: http://en.wikipedia.org/wiki/Singleton_pattern
Upvotes: 3
Reputation: 168825
The best solution is to open a modal dialog instead of the frame. See The Use of Multiple JFrames, Good/Bad Practice? for more.
Upvotes: 3