简体   繁体   English

为新的JFrame创建新线程

[英]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. 我正在尝试制作2帧,其中一个是主框架,另一个将在单击按钮后显示。 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. 仅2帧,每个按钮都有一个按钮就足够了。 Much appreciated! 非常感激!

You should avoid the use of multiple JFrame s , use modal dialogs instead. 您应该避免使用多个JFrame ,而应使用模式对话框 JOptionPane offers a ton of good, easy & flexible methods to do so. JOptionPane提供了很多好的,简单和灵活的方法来做到这一点。

Here's an example. 这是一个例子。 When you click the button the dialog will appear on top of the JFrame . 当您单击按钮时,对话框将出现在JFrame顶部。 The main JFrame won't be clickable anymore, since JOptionPane.showMessageDialog() produces a modal window . 由于JOptionPane.showMessageDialog()生成一个模式窗口 ,因此不再可单击主JFrame

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: 输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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