我在Thread.Sleep方法中显示对话框时遇到问题这里是我的代码,它不起作用。
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JDialog loading = new LoadingDialog();
loading.setVisible(true);
try {
Thread.sleep(6000);
} catch (Exception e) {
e.printStackTrace();
}
loading.dispose();
}
});
和
public class LoadingDialog extends JDialog {
public LoadingDialog(){
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setBounds((screenWidth-400)/2, (screenHeight-200)/2, 350, 80);
getContentPane().setLayout(null);
setResizable(false);
setUndecorated(true);
JLabel lblPleaseWaitWhile = new JLabel("Please wait while starting the services.");
lblPleaseWaitWhile.setBounds(85, 22, 313, 14); getContentPane().add(lblPleaseWaitWhile);
setVisible(true);
}
}
帮我解决这个问题。
答案 0 :(得分:0)
使用自定义对话框,您将阻止主线程 - 请尝试此操作;
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final JDialog loading = new LoadingDialog();
loading.setVisible(true);
btn.setEnabled(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
}
loading.dispose();
btn.setEnabled(true);
}
}).start();
}
});
答案 1 :(得分:0)
在这种情况下,最好使用SwingWorker。此类允许您创建以后台模式运行的线程。它适用于模态框架。