简体   繁体   中英

Create new thread for a new JFrame

I'm learning about threads and I've got a problem with it. I'm trying to make 2 frames, one is a main frame and another will be shown later after clicking on a button. I want to stop the main frame while the new frame is running. Can you guys help me with a very simple example for this? (And the new frame will be closed after clicking on a button too). Just 2 frames with a button on each are enough. Much appreciated!

You should avoid the use of multiple JFrame s , use modal dialogs instead. JOptionPane offers a ton of good, easy & flexible methods to do so.

Here's an example. When you click the button the dialog will appear on top of the JFrame . The main JFrame won't be clickable anymore, since JOptionPane.showMessageDialog() produces a modal window .

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Example {

    public Example() {

        JFrame frame = new JFrame();

        JButton button = new JButton("Click me");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(frame, "I'm a dialog!");
            }
        });

        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(button);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Example();
            }
        });
    }


}

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM