Search code examples
javaswingnetbeansmdijmenuitem

How to prevent multiple instances of MDI child forms in netbeans


Im developing a java app with MDI application forms. I have assigned menu items to open two internal child forms. when i click them repetitively they create instances for each click how can i stop this and show the previously instantiated form at the first click.

here is the code for the action listener for the menu item im using,

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        RecognitionForm recForm=new RecognitionForm();
        desktopPane.add(recForm);
        recForm.setVisible(true);

}

Solution

  • I can think of two ways.

    The first is to raise a flag when you create the frames. The problem here is the fact that you will need to monitor for when the frames are closed, which adds additional overhead.

    The second is to check all the frames currently open on the desktop for the instance of the frame, using `JDesktopPane#getAllFrames'.

    From there you would simply loop through the result doing either a instanceof of comparing the title (for example) and if you don't find any, create them, otherwise you could use JDesktopPane.selectFrame to highlight it