java - 在 Java Swing 中处理 ProgressBar
问题描述
我正在使用 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 的规则。
推荐阅读
- opencv - 有没有办法知道安装 OpenCV 的选项?
- css - Shiny中的动态大标签$ img
- android - ViewPager2:以编程方式选择特定片段
- python - Docker 运行 Flask ImportError: No Module Named Flask
- r - 我如何计算这个数据框?
- android - 如何在 Android 中使用 Paging 3 库观察 Room 中更改的项目
- python - Python Unittest模拟问题
- c# - How to update every row using this function in database by getting the id of every row?
- python - 合并两个不同维度的数据框
- reactjs - 当组件需要一个对象时,如何将函数作为道具传递?