3

我正在尝试为应用程序制作登录屏幕。在登录期间,将对 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();

我现在放了一些虚拟事件,但状态标签没有改变......有什么建议吗?

4

4 回答 4

4

一个简单的摇摆工人解决了它。我想我在谷歌上做得不够好

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));
    }

}
于 2012-10-12T23:58:36.783 回答
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;
    }
}
于 2012-10-13T00:09:22.133 回答
1

您不应在事件分派线程上执行任何长时间运行的操作。您正在执行一个需要 3 秒才能完成的操作。在这 3 秒内,您将独占 EDT,并且不会发生其他 GUI 更新。

于 2012-10-12T23:58:12.940 回答
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您从未真正开始它是没有意义的。

为了将来参考,我将仔细研究Java 中的并发

您是正确的(在您的自我回答中),SwingWorker这是一个更容易的解决方案。

于 2012-10-13T01:30:47.910 回答