簡體   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