EDT location with several JFrame window

后端 未结 3 1471
梦毁少年i
梦毁少年i 2020-12-21 07:26

I have a Swing JFrame. If I create a new JFrame in a new thread during the program execution where will be the EDT ? In the current thread of the last JFrame window or in t

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 08:26

    The EDT - the event dispatch thread - is separate from any concrete GUI component, such as a JFrame.

    Generally you should create all GUI components on the EDT, but that does not mean they own the EDT, nor does the EDT own the components.

    To create two JFrames, both on the EDT, you can do the following:

    public static void main(String[] args) {
    
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame1 = new JFrame("Frame 1");
                frame1.getContentPane().add(new JLabel("Hello in frame 1"));
                frame1.pack();
                frame1.setLocation(100, 100);
                frame1.setVisible(true);
            }
        });
    
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame2 = new JFrame("Frame 2");
                frame2.getContentPane().add(new JLabel("Hello in frame 2"));
                frame2.pack();
                frame2.setLocation(200, 200);
                frame2.setVisible(true);
            }
        });
    
    }
    

提交回复
热议问题