Java Swing How to - Close one JFrame without closing another








Question

We would like to know how to close one JFrame without closing another.

Answer

import java.awt.BorderLayout;
//www .  j  av  a 2s  .c  o m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    int nb = 4;
    final int frameCount = nb;

    for (int i = 0; i < frameCount; i++) {
      JFrame frame = new JFrame("Frame number " + i);
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      JPanel p = new JPanel(new BorderLayout());
      p.add(new JLabel("Click on the corner to close..."), BorderLayout.CENTER);
      frame.setContentPane(p);
      frame.setSize(200, 200);
      frame.setLocation(100 + 20 * i, 100 + 20 * i);
      frame.setVisible(true);
    }
  }
}