Ner*_*Guy 0 java swing multithreading
我正在学习线程,但遇到了问题。我正在尝试制作 2 个框架,一个是主框架,另一个将在单击按钮后显示。我想在新框架运行时停止主框架。你们能帮我举一个非常简单的例子吗?(单击按钮后,新框架也将关闭)。只需 2 个带有按钮的框架就足够了。非常感激!
您应该避免使用多个JFrames,而应使用模态对话框。JOptionPane提供了大量好的、简单和灵活的方法来做到这一点。
这是一个例子。当您单击该按钮时,对话框将出现在JFrame. mainJFrame将不再可点击,因为JOptionPane.showMessageDialog()会生成一个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();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
输出: