2

I'm currently writing a Desktop-Application with Swing that consists of a MainFrame in which several InternalFrames will be running. I want to write the InternalFrames in separate classes for each to avoid having one huge MainFrame-class.

Now my problem is that I want to add an ActionListener to a MenuItem in a PopupMenu in the MenuInternalFrame that opens another InternalFrame in the MainFrame. The MenuInternalFrame appears, however when I click on the MenuItem nothing happens. When I put the code outside of the ActionListener the InternalFrame appears.

The problem must be something with the ActionListener. Could it be my workaround with the local class and a final instance to access the InternalFrame from within the mouseClicked-Method?

Here are the relevant parts of the code from the MainFrame-Constructor:

class InternalFrames {
    TestInternalFrame test = new TestInternalFrame();
    JDesktopPane desktopPane = new JDesktopPane();
}

final InternalFrames internalFrames = new InternalFrames();

internalFrames.desktopPane.setBackground(Color.WHITE);

Menu menu = new Menu();
menu.getMntmTestMenuItem().addMouseListener( new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        internalFrames.desktopPane.add(internalFrames.test);
        internalFrames.test.setVisible(true);
    }
});
internalFrames.desktopPane.add(menu);
menu.setVisible(true);

Any ideas what could be the problem? Thanks in advance.

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138

1 Answers1

2

Dont use MouseAdapter on a JMenuItem, use ActionListener and add it via JMenuItem#addActionListener(...) instead:

Menu menu = new Menu();
menu.getMntmTestMenuItem().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            internalFrames.desktopPane.add(internalFrames.test);
            internalFrames.test.setVisible(true);
    }
});
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138