我目前正在开发数据库程序,但遇到了问题。我正在尝试创建一个 JFrame 来提示用户做什么,然后当他们单击按钮时,会调用另一个类中的方法(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 将立即关闭。如果您仍想等待几秒钟,请尝试在调用 f.dispose(); 之前添加行 TimeUnit.SECONDS.sleep(1);
// 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();
}
});
希望有帮助。
附注另外,您可能想检查是否使用 JDialog 来实现此目的,而不是 JFrame,会更好。
关于java - 单击 JButton 后创建延迟关闭 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61938132/