I created MDI (Multiple Document interface) in java using netbeans in which i have two jbuttons and one jdesktoppane so when clicked on both button then both jinternalframes are opened in same jdesktoppane so i want how to close previous jinternalframe when open new jinternalframe in the jdesktoppane ?
Check snapshot for more better understand my question what i want…

First jButton code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
tst t = new tst();
JInternalFrame internalFrame1 = new JInternalFrame("Test Window1");
internalFrame1.add(t.getContentPane());
internalFrame1.pack();
internalFrame1.setVisible(true);
q.add(internalFrame1);
internalFrame1.setClosable(true);
BasicInternalFrameUI ui = (BasicInternalFrameUI)internalFrame1.getUI();
Container north = (Container)ui.getNorthPane();
north.remove(0);
north.validate();
north.repaint();
for(MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) internalFrame1.getUI()).getNorthPane().getMouseListeners()){
((javax.swing.plaf.basic.BasicInternalFrameUI) internalFrame1.getUI()).getNorthPane().removeMouseListener(listener);
}
internalFrame1.setSelected(true);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
Second button Code:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
zxy z = new zxy();
JInternalFrame internalFrame = new JInternalFrame("Test Window2");
internalFrame.add(z.getContentPane());
internalFrame.pack();
internalFrame.setSize(570,420);
internalFrame.setVisible(true);
q.add(internalFrame);
internalFrame.setClosable(true);
BasicInternalFrameUI ui = (BasicInternalFrameUI)internalFrame.getUI();
Container north = (Container)ui.getNorthPane();
north.remove(0);
north.validate();
north.repaint();
for(MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) internalFrame.getUI()).getNorthPane().getMouseListeners()){
((javax.swing.plaf.basic.BasicInternalFrameUI) internalFrame.getUI()).getNorthPane().removeMouseListener(listener);
}
internalFrame.setSelected(true);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
Simply call
dispose()onJInternalFrameinstance.To do this you will need to move your
JInternalFramedeclaration out of the method so that we may check if the instance is notnull(thus there is an existing instance and than calldispose()on the instance before creating a new one: