Close one JFrame without closing another?

前端 未结 2 716
自闭症患者
自闭症患者 2020-11-27 16:37

I want to display two (or more) JFrames at the same time.
When I close one of them (use the default close button), the other frames should still be visible.

2条回答
  •  误落风尘
    2020-11-27 17:33

    Does it help you ?

    import java.awt.BorderLayout;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class TwoJFrames {
        public static void main(String[] args) {
            int nb = 4;
            if (args != null && args.length > 0) {
                nb = Integer.parseInt(args[0]);
            }
    
            final int frameCount = nb;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    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);
                    }
                }
            });
    
        }
    }
    

提交回复
热议问题