我正在尝试为应用程序创建登录屏幕。在登录期间,将对MySQL数据库进行许多SQL调用,并且可能需要几秒钟来设置所有内容。我想通过卡片布局显示状态屏幕,并在后台线程运行时更新JLabel。
这是我对工人线程的要点:
public class LoginPrepThread extends Thread {
private final UIMain parent;
public LoginPrepThread(UIMain w){
parent = w;
}
public void exec(){
EventQueue.invokeLater(this);
}
public void run(){
try{
//SqlHelper sql = SqlHelper.instance;
sleep(500);
parent.getLoadingLable().setText("Fetching preferences...");
parent.getMainFrame().revalidate();
sleep(500);
parent.getLoadingLable().setText("Scanning workbench...");
parent.getMainFrame().revalidate();
sleep(500);
parent.getLoadingLable().setText("Updating permissions...");
parent.getMainFrame().revalidate();
sleep(500);
parent.getLoadingLable().setText("Finished...Please wait");
parent.getMainFrame().revalidate();
sleep(1000);
parent.getLayout().show(parent.getMainFrame().getContentPane(), "view.main");
}catch(Exception e){
}
}
}
以下是我如何调用它(在JButton事件中,在进行身份验证后):
setActiveProfile(user);
layout.show(frame.getContentPane(), "view.loading");
frame.repaint();
LoginPrepThread pt = new LoginPrepThread(thisTrick);
pt.exec();
我现在放了一些虚拟事件,但状态标签没有改变......有什么建议吗?
答案 0 :(得分:4)
一个简单的摇摆工人解决了它。我想我的google'ing
还不够好public class LoginPrepThread extends SwingWorker<String,String> {
private final UIMain parent;
public LoginPrepThread(UIMain w){
parent = w;
}
@Override
protected String doInBackground() throws Exception {
try{
publish("Fetching preferences...");
Thread.sleep(1000);
publish("Updating permissions...");
Thread.sleep(1000);
publish("Scanning workbench...");
Thread.sleep(1000);
publish("Finalizing...");
Thread.sleep(2000);
publish("Finished...Please wait");
Thread.sleep(1000);
parent.getLayout().show(parent.getMainFrame().getContentPane(), "view.main");
}catch(Exception e){
}
return null;
}
protected void process(List<String> item) {
parent.getLoadingLable().setText(item.get(0));
}
}
答案 1 :(得分:3)
理想情况下,您将实现SwingWorker来执行所有繁重的非GUI相关任务。你应该利用事件驱动编程的优势。
你需要做的是这样的事情:
在GUI类中实现PropertyChangeListner,监听更新。根据属性更改,更新标签。使用单个GUI类处理所有与GUI相关的更新活动始终是一种好习惯。
创建一个SwingWorker,您可以在其中执行背景密集型任务。当有可用的更新时,触发属性更改事件并让GUI类知道有更新。
以下是您可以做的小SSCCE示例:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.SwingWorker;
/**
*
* @author Sujay
*/
public class SimpleWorkerUI extends javax.swing.JFrame implements PropertyChangeListener{
/**
* Creates new form SimpleWorkerUI
*/
public SimpleWorkerUI() {
initComponents();
Worker worker = new Worker();
worker.addPropertyChangeListener(this);
worker.execute();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Current Status: ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addContainerGap(327, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addContainerGap(20, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SimpleWorkerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SimpleWorkerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SimpleWorkerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SimpleWorkerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SimpleWorkerUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
// End of variables declaration
@Override
public void propertyChange(PropertyChangeEvent evt) {
if("status".equalsIgnoreCase(evt.getPropertyName())){
String currentStatus = (String) evt.getNewValue();
jLabel2.setText(currentStatus);
}
}
}
class Worker extends SwingWorker<String, String>{
private static final int FINAL_VALUE = 1000;
@Override
protected String doInBackground() throws Exception {
int counter = 0;
while(counter < FINAL_VALUE){
firePropertyChange("status", "", "value is: "+counter);
try{
Thread.sleep(100);
}catch(InterruptedException ixe){
}
counter++;
}
return null;
}
}
答案 2 :(得分:1)
您不应对事件派发线程执行任何长时间运行的操作。您正在执行一项需要3秒钟才能完成的操作。在这3秒钟内,您正在垄断EDT,并且不会发生其他GUI更新。
答案 3 :(得分:0)
你出于善意开始......
public class LoginPrepThread extends Thread {
private final UIMain parent;
public LoginPrepThread(UIMain w){
parent = w;
}
public void exec(){
EventQueue.invokeLater(this);
}
public void run(){
try{
//SqlHelper sql = SqlHelper.instance;
sleep(500);
parent.getLoadingLable().setText("Fetching preferences...");
parent.getMainFrame().revalidate();
sleep(500);
parent.getLoadingLable().setText("Scanning workbench...");
parent.getMainFrame().revalidate();
sleep(500);
parent.getLoadingLable().setText("Updating permissions...");
parent.getMainFrame().revalidate();
sleep(500);
parent.getLoadingLable().setText("Finished...Please wait");
parent.getMainFrame().revalidate();
sleep(1000);
parent.getLayout().show(parent.getMainFrame().getContentPane(), "view.main");
}catch(Exception e){
}
}
}
基本上,发生了什么,就是当你打电话给exec
实际向EDT发出请求以调用run
方法时,然后在EDT中执行该方法,导致堵塞。
此外,在您的原始示例中,从Thread
延伸,因为您从未真正开始它,这是毫无意义的。
为了将来参考,我会仔细研究Concurrency in Java
你是对的(在你自己的回答中),SwingWorker
是一个更容易的解决方案。