我想显示一系列消息几秒钟,并在连接到数据库期间消失。我该如何在 Java 中做到这一点?
第一条消息应显示“连接到数据库”,第二条消息应显示“正在创建数据库”,最后一条消息应显示“数据库创建成功”。
这是该类的代码。我只是想用弹出窗口替换 println 语句,几秒钟后将其关闭。
public class ExecuteSQL {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/?allowMultiQueries=true";
// Database credentials
static final String USER = "root";
static final String PASS = "";
public static void connectExe() {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = Domain.getCurrentDatabaseSQL();
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}//end try
}
}
我正在使用 Swing。
最佳答案
实际显示消息的方法有很多种,您可以在玻璃板上使用 JPanel
,您可以使用无框 window ,您可以......但我们不用担心这一点。
在 Swing 中触发 future 事件的最简单、最好的方法可能是使用 javax.swing.Timer
。它使用起来简单直接,并且在 Swing 中使用是安全的。
Swing 不是线程安全的并且是单线程的。这意味着您永远不应该使用可能需要时间来运行或暂停 EDT 执行的代码来阻塞事件调度线程,并且永远不应该与 EDT 外部的任何 UI 组件进行交互。
javax.swing.Timer
是等待指定时间段而不阻塞 EDT 的好方法,但会在 EDT 上下文中触发其更新,使其易于使用并且可以安全地从内部与 UI 组件交互...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class ShowMessage {
public static void main(String[] args) {
EventQueue.invokeLater(
new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setLayout(new GridBagLayout());
((JComponent)frame.getContentPane()).setBorder(new EmptyBorder(20, 20, 20, 20));
frame.add(new JLabel("Boo"));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
timer.setRepeats(false);
timer.start();
}
}
);
}
}
参见Concurrency in Swing和 How to Use Swing Timers了解更多详情
已更新
如果您运行的背景长度未知,则可以使用 SwingWorker
来代替。这将允许您在 doInBackground
方法中运行任务,完成后,将调用 done
方法,您可以关闭消息弹出窗口
关于java - 如何在长时间运行的任务中显示消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25946128/