0

I am creating more than one JInternalFrame in the JDesktopPane. Each frame having one button. I want to close the particular frame on which button is clicked.

internalFrame = new JInternalFrame("Internal Frame", true, true, true, true);

    internalFrame.setSize(300, 300);
    internalFrame.setLocation(xPosition * openFrameCount, yPosition
            * openFrameCount);

    internalFrame.setContentPane(createContentPane());
    internalFrame.setJMenuBar(createPopJMenuBar());

    internalFrame.setVisible(true);

    JButton close = new JButton( "Close Me!" );  
    close.addActionListener( new ActionListener() {  
        public void actionPerformed( ActionEvent e ) {
                try {
                    internalFrame.setClosed( true );
                } catch (PropertyVetoException e1) {
                    e1.printStackTrace();
                }
        }  
    } );  
    internalFrame.add( close );  
    jdpDesktop.add(internalFrame);

By using the above code I am able to close the last created frame. Other frames are not closed.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Raja
  • 239
  • 1
  • 5
  • 18
  • I want to close the particular JFrame on which button is clicked. ---> my question JFrame or JInternalFrame, could be quite different – mKorbel Aug 17 '13 at 12:38

1 Answers1

1

Looks like you have internalFrame as a field of the enclosing class. Then it gets overwritten every time you create a new one. Use a local variable instead:

// Notice "final"
final JInternalFrame internalFrame = new JInternalFrame("Internal Frame", true, true, true, true);
...

That ensures that the internalFrame in each action listener refers to the one created a few lines above, not to the last created frame.

kiheru
  • 6,588
  • 25
  • 31
  • great man..it works fine.Can i able to do the same thing using menu in each jframe ? – Raja Aug 17 '13 at 12:40
  • 1
    @Raja I don't know what do you mean with the menues :-) It's quite possible that you have the same bug pattern there. If you are binding a listener to a menu created locally but assigned it to a field, that seems likely. Generally it's good idea to use local variables unless you actually need to store it in a field. – kiheru Aug 17 '13 at 12:45