[英]Create new thread for a new JFrame
我正在學習線程,但遇到了問題。 我正在嘗試制作2幀,其中一個是主框架,另一個將在單擊按鈕后顯示。 我想在新框架運行時停止主框架。 你們能幫我舉一個非常簡單的例子嗎? (新框也將在單擊按鈕后關閉)。 僅2幀,每個按鈕都有一個按鈕就足夠了。 非常感激!
您應該避免使用多個JFrame
,而應使用模式對話框 。 JOptionPane
提供了很多好的,簡單和靈活的方法來做到這一點。
這是一個例子。 當您單擊按鈕時,對話框將出現在JFrame
頂部。 由於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();
}
});
}
}
輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.