[英]Create a delay to close JFrame after a JButton is clicked
我目前正在開發數據庫程序,但遇到了問題。 我正在嘗試創建一個 JFrame 來提示用戶做什么,然后當他們單擊一個按鈕時,另一個 class 中的方法被調用(db.createDB()或 db.openDB())。 我不確定如何添加計時器以僅在單擊其中一個按鈕后處理框架。
提前致謝! ~傑瑞德
這是我的代碼:
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
*
* @author Jared Rathbun
*/
public class Driver {
private Database db;
private IDCount count;
Driver() {
// Initialize the DB and IDCounter.
db = new Database();
count = new IDCount();
try {
// Set the look and feel to the system default.
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | IllegalAccessException
| InstantiationException | UnsupportedLookAndFeelException e) {
System.out.println("Look and Feel not set");
}
JFrame f = new JFrame("Select an Option");
JLabel label = new JLabel("What would you like to do?");
label.setBounds(8,10,390,50);
JButton newDBButton = new JButton("Create a New Database");
newDBButton.setBounds(30,75,150,45);
JButton openDBButton = new JButton("Open a Database");
openDBButton.setBounds(210,75,150,45);
label.setFont(new Font("Tahoma", Font.PLAIN, 16));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setVerticalAlignment(SwingConstants.CENTER);
f.add(newDBButton);
f.add(openDBButton);
f.add(label);
f.setSize(400,200);
f.setLayout(null);
f.setResizable(false);
f.setVisible(true);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add actionListeners for both buttons.
newDBButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
db.createDB();
}
});
openDBButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
db.openDB();
}
});
// NEEDS TO CLOSE A FEW SECONDS AFTER ONE OF THE BUTTONS IS CLICKED
}
public static void main(String[] args) {
new Driver();
}
}```
在調用 dc.createDB() 和/或 db.openDB() 之后,嘗試在每個按鈕偵聽器中添加對 f.dispose() 的調用。 這樣,dc.createDB 和 db.openDB 代碼將執行,然后框架 f 將立即關閉。 如果您仍想等待幾秒鍾,請嘗試添加行TimeUnit.SECONDS.sleep(1); 在調用 f.dispose() 之前;
// Add actionListeners for both buttons.
newDBButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
db.createDB();
f.dispose()
}
});
openDBButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
db.openDB();
try {
TimeUnit.SECONDS.sleep(3); // wait 3 seconds
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
f.dispose();
}
});
希望能幫助到你。
PS 另外,您可能想檢查是否為此目的使用 JDialog,而不是 JFrame,會更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.