繁体   English   中英

在 Java Swing 中处理 ProgressBar

[英]Handling ProgressBar in Java Swing

我正在使用 swing 构建一个实用程序,我需要在实用程序运行后端活动时运行进度条。 一旦活动结束,进度条就应该停止,指示用户实用程序已准备好进行下一步操作。

在下面的代码中,我添加了一个按钮和一个进度条,并试图在 5 秒内迭代控制进度条。 但是,看起来像“执行的操作”事件没有进行迭代。在这种情况下,它永远不会触发进度条。如果我只提到"jProgressBar1.setIndeterminate(true);"那么我会在单击按钮时看到进度条。所以,请帮帮我关于如何在另一个按钮事件中控制进度条。

public class SampleSwingExample extends javax.swing.JFrame {

/**
 * Creates new form NewJFrame
 */
public SampleSwingExample() {
    initComponents();
}

/**
 * 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() {

    jProgressBar1 = new javax.swing.JProgressBar();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            try {
                jButton1ActionPerformed(evt);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap(128, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(126, 126, 126))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addGap(145, 145, 145))))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(100, 100, 100)
            .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton1)
            .addContainerGap(133, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) throws InterruptedException {                                         
    // TODO add your handling code here:
    
    jProgressBar1.setIndeterminate(true); 
    Thread.sleep(5000);
    jProgressBar1.setIndeterminate(false); 
    Thread.sleep(2000);
    jProgressBar1.setIndeterminate(true); 
    Thread.sleep(5000);
    jProgressBar1.setIndeterminate(false); 
}                                        

/**
 * @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(SampleSwingExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(SampleSwingExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(SampleSwingExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(SampleSwingExample.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 SampleSwingExample().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JProgressBar jProgressBar1;
// End of variables declaration                   

}

任何帮助高度赞赏。 谢谢

您应该仔细阅读如何在 Swing 上执行后台作业。Swing 中的界面在事件调度线程 (EDT) 上运行。 EDT 不能停止,否则您的界面将变得无响应。 但是,一旦有其他线程,就只允许 EDT接触界面元素。 所以这段代码是一个非常糟糕的主意,因为它使界面无响应:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) 
        throws InterruptedException {                                         

    jProgressBar1.setIndeterminate(true); 
    Thread.sleep(5000);                      // <-- interface unresponsive
    jProgressBar1.setIndeterminate(false); 
    Thread.sleep(2000);                      // <-- interface unresponsive
    jProgressBar1.setIndeterminate(true); 
    Thread.sleep(5000);                      // <-- interface unresponsive
    jProgressBar1.setIndeterminate(false); 
}

相反,您应该在不同的线程中启动后台作业,并让它们根据需要通知 UI:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    Runnable r = () -> {
        signalProgress(true);
        Thread.sleep(5000);
        signalProgress(false);
        Thread.sleep(2000);
        signalProgress(true);
        Thread.sleep(5000);
        signalProgress(false);

    };
    new Thread(r).start(); // starts a new thread that runs 'r'
}

// this code can be called from any thread
public void signalProgress(final boolean indeterminate) {
    // because SwingUtils.invokeLater executes code safely in the EDT
    // without invokeLater, the interface state could become corrupted
    SwingUtils.invokeLater(() -> jProgressBar.setIndeterminate(indeterminate));
}

请注意,有更好的方法可以做到这一点。 例如,创建SwingWorker是为了简化从 Swing 启动后台任务,而不会弄乱 EDT 的规则。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM