Search code examples
javaswingjinternalframesingle-instance

Allow only one instance of JInternalFrame


I've created a Swing application with several JInternalFrames which gets added to a JDesktopPane on the event of a mouse click. I want only one instance of the same Internal frame to be present on the DesktopPane. I dont want the same frame to appear twice when the user opens the frame. If the frame is already open, then a error message should appear.!

Thanks a lot :)


Solution

  • Don't bother with a singleton anti-pattern. Instead simply give your class a JInternalFrame field and create one instance of your JInternalFrame in your class's constructor or at variable declaration, and don't create a new one on mouse click, but rather display the one that has been already created. For instance in the mousePressed method, simply call myInternalFrame.setVisible(true). This way, if it was invisible, now it's visible, and if it's already visible, then it's still visible and unchanged. Simple and straightforward.