更新 SwingWorker 中的 JProgressBar。

huangapple go评论141阅读模式
英文:

Update JProgressBar from a SwingWorker

问题

// 以下是你的代码部分翻译结果:

import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

public class JFrame_Demo extends javax.swing.JFrame {
    // ... 省略其他变量声明

    public JFrame_Demo() throws FontFormatException, IOException, InterruptedException {
        setTitle("Database Statistics Execution");
        initComponents();
        getContentPane().setBackground(Color.WHITE);
        setBackground(Color.white);
        setResizable(false);
        setSize(800, 800);
        pack();
        setVisible(true);
    }

    // ... 省略其他方法

    private void initComponents() throws FontFormatException, IOException, InterruptedException {
        // ... 省略组件初始化

        jButton1.setText("Submit");

        Exp_Schema_Check.setText("Exp_Schema_Check");

        DB_Parameters_Sizing_Details.setText("DB_Parameters_Sizing_Details");

        Redo_Archive_Details.setText("Redo_Archive_Details");

        Session_Details.setText("Session_Details");

        Tablespaces_Details.setText("Tablespaces_Details");

        SPM_Performance_Details.setText("SPM_Performance_Details");

        JLabel Hostname = new JLabel();
        Hostname.setText("Enter the Database Hostname");

        host = new JTextField();

        JLabel lblEnterTheDatabase = new JLabel();
        lblEnterTheDatabase.setText("Enter the Database Port");

        Port = new JTextField();

        JLabel syspass_label = new JLabel();
        syspass_label.setText("Enter Database System Password");

        JLabel lblPoweredByDs = new JLabel();
        lblPoweredByDs.setForeground(new Color(51, 102, 204));

        lblPoweredByDsgs = new JLabel();
        lblPoweredByDsgs.setForeground(new Color(0, 153, 255));
        lblPoweredByDsgs.setText("Powered By DSGS Infra Team");

        selectall = new JCheckBox("Select All");

        progressBar = new JProgressBar();
        progressBar.setStringPainted(true);

        // ... 组件布局代码
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        // ... 外观设置

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new JFrame_Demo().setVisible(true);
                } catch (FontFormatException | IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

这是你提供的Java代码的翻译结果。如有需要,请随时问我问题。

英文:

I am new to Java and trying to build an application that receives 6 inputs from JSwing TextFields.
I have around 5 checkboxes. Based on the selection, some of the details are fetched from database.
All other things are working now, but I want to place a progress bar that updates the value based on the progress. I tried manually updating the ProgressBars with progressBar.setValue(0) to progressBar.setValue(100) across checkboxes. But it did not get updated. After going through some of the articles online, I found using swing worker from this link. I tried Robin's solution.
https://stackoverflow.com/questions/10236995/how-do-i-make-my-swingworker-example-work-properly/10240173#10240173 . It creates a separate dialog but, it is empty.

Showing Progress like this

Is there a way I can set progress bar updating in my program?

        jButton1 = new javax.swing.JButton();
jButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
progressBar.setValue(0);
if(Sizing_details.isSelected()) {
progressBar.setValue(20); 
}

Then I tried using swing worker from the link I mentioned.

                    public void actionPerformed(ActionEvent e) {
new GuiWorker().execute();

The dialog is struck and nothing shows up. But Functionality wise it works. Could you please help me how I can fix it.

I have two questions.

  1. Is it possible to update ProgressBar manually whenever I set them inside a checkbox under submit button action. ?
  2. If I have to use swing worker, is it possible to add a progressbar in the same frame and manipulate it.

EDIT I:

I can make the Progress bar pop up. However, When I call the "go" method from the link below
https://stackoverflow.com/questions/20260372/swingworker-progressbar

inside my Jbutton action event , it shows a blank screen.

But when I call the same method inside run method it works fine.

            java.awt.EventQueue.invokeLater(new Runnable() {
public void run() { go();
try {
new JFrame_Demo().setVisible(true);
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

The above code works. it initialises a progress bar.

              java.awt.EventQueue.invokeLater(new Runnable() {
public void run() { 
try {
new JFrame_Demo().setVisible(true);
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
go();

the above code shows a blank white screen.

    import java.awt.Color;
import java.awt.Dialog;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.ibm.java.diagnostics.utils.plugins.Container;
import com.ibm.jvm.trace.format.api.Component;
import com.sun.tools.javac.util.List;
import javax.swing.JToolBar;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JCheckBox;
import dbutility.*;
public class JFrame_Demo extends javax.swing.JFrame {
/**
* 
*/
private static final long serialVersionUID = 1L;
/**
* Creates new form JFrame_Demo
* @throws IOException 
* @throws FontFormatException 
* @throws InterruptedException 
*/
public JFrame_Demo() throws FontFormatException, IOException, InterruptedException {
setTitle("Database Statistics Execution");
initComponents();
getContentPane().setBackground(Color.WHITE);
setBackground(Color.white);
setResizable(false);
setSize(800,800);
pack();
setVisible(true);
}
/**
* 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.
* @throws IOException 
* @throws FontFormatException 
* @throws InterruptedException 
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() throws FontFormatException, IOException, InterruptedException {
Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("lib\\Font\\3ds_Regular.otf")).deriveFont(12f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(customFont);
DBUser_Input = new javax.swing.JLabel();
DBUser_Input.setFont(customFont);
DBUser_Input.setToolTipText("Database System User");
Schema = new javax.swing.JTextField();
space_user_lable = new javax.swing.JLabel();
space_user_lable.setFont(customFont);
jLabel4 = new javax.swing.JLabel();
jLabel4.setFont(customFont);
jLabel5 = new javax.swing.JLabel();
jLabel5.setFont(customFont);
Username = new javax.swing.JTextField();
Instance = new javax.swing.JTextField();
syspassword = new javax.swing.JPasswordField();
schema_password = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
JProgressBar pb = new JProgressBar();
getContentPane().add(pb);
jButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e ) {
new GuiWorker().execute();
String schema = Schema.getText();
String Schema_Password = schema_password.getText();
String port = Port.getText();
String instance = Instance.getText();
String Host = host.getText();
String URL = "jdbc:oracle:thin:@"+Host+":"+port+":"+instance;
String dbpassword = syspassword.getText();
String username = Username.getText();
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection(URL,username,dbpassword);
if(Exp_Schema_Check.isSelected()) {
// PROGRESS BAR TO BE SET TO 20
//Execute 20 database queries....
}
if(DB_Parameters_Sizing_Details.isSelected()) {
// PROGRESS BAR TO BE SET TO 50
//Execute 12 Database queries
}
if(Redo_Log.isSelected()) {
PROGRESS BAR TO BE SET TO 75
//... Execute 35 queries. . 
}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
}
);
Exp_Schema_Check = new javax.swing.JCheckBox();
DB_Parameters_Sizing_Details = new javax.swing.JCheckBox();
DB_Parameters_Sizing_Details.setFont(customFont);
Redo_Archive_Details = new javax.swing.JCheckBox();
Redo_Archive_Details.setFont(customFont);
Session_Details = new javax.swing.JCheckBox();
Session_Details.setFont(customFont);
Tablespaces_Details = new javax.swing.JCheckBox();
Tablespaces_Details.setFont(customFont);
SPM_Performance_Details = new javax.swing.JCheckBox();
SPM_Performance_Details.setFont(customFont);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
DBUser_Input.setText("Enter Database System Username");
Schema.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
space_user_lable.setText("Enter 3DSpace Username");
jLabel4.setText("Enter Instance Name");
jLabel5.setText("Enter 3DSpace Password");
Username.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
Instance.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField4ActionPerformed(evt);
}
});
jButton1.setText("Submit");
Exp_Schema_Check.setText("Exp_Schema_Check");
Exp_Schema_Check.setFont(customFont);
DB_Parameters_Sizing_Details.setText("DB_Parameters_Sizing_Details");
Redo_Archive_Details.setText("Redo_Archive_Details");
Session_Details.setText("Session_Details");
Tablespaces_Details.setText("Tablespaces_Details");
SPM_Performance_Details.setText("SPM_Performance_Details");
JLabel Hostname = new JLabel();
Hostname.setFont(customFont);
Hostname.setText("Enter the Database Hostname");
host = new JTextField();
JLabel lblEnterTheDatabase = new JLabel();
lblEnterTheDatabase.setFont(customFont);
lblEnterTheDatabase.setText("Enter the Database Port");
Port = new JTextField();
JLabel syspass_label = new JLabel();
syspass_label.setFont(customFont);
syspass_label.setText("Enter Database System Password");
JLabel lblPoweredByDs = new JLabel();
lblPoweredByDs.setForeground(new Color(51, 102, 204));
lblPoweredByDs.setToolTipText("Database System User");
lblPoweredByDs.setFont(customFont);
lblPoweredByDs.setFont(customFont);
lblPoweredByDsgs = new JLabel();
lblPoweredByDsgs.setForeground(new Color(0, 153, 255));
lblPoweredByDsgs.setText("Powered By DSGS Infra Team");
lblPoweredByDsgs.setFont(null);
selectall = new JCheckBox("Select All");
selectall.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent arg0) {
if(selectall.isSelected()) {
Exp_Schema_Check.setSelected(true);
DB_Parameters_Sizing_Details.setSelected(true);
Redo_Archive_Details.setSelected(true);
Session_Details.setSelected(true);
SPM_Performance_Details.setSelected(true);
Tablespaces_Details.setSelected(true);
}
else if(selectall.isSelected()==false) {
Exp_Schema_Check.setSelected(false);
DB_Parameters_Sizing_Details.setSelected(false);
Redo_Archive_Details.setSelected(false);
Session_Details.setSelected(false);
SPM_Performance_Details.setSelected(false);
Tablespaces_Details.setSelected(false);
}
}
});
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(space_user_lable)
.addComponent(Hostname)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(DBUser_Input)
.addComponent(jLabel5))
.addGap(105)
.addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(Username, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE)
.addComponent(Schema, GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addComponent(schema_password, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(Instance, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addComponent(host, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addComponent(syspassword, Alignment.LEADING)
.addComponent(Port, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)))
.addComponent(lblPoweredByDs, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 149, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(1427, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(syspass_label, GroupLayout.DEFAULT_SIZE, 1312, Short.MAX_VALUE)
.addGap(612))))
.addGroup(layout.createSequentialGroup()
.addGap(30)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(selectall)
.addGap(381)
.addComponent(progressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(Exp_Schema_Check)
.addComponent(DB_Parameters_Sizing_Details)
.addComponent(Redo_Archive_Details)
.addComponent(Session_Details)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(SPM_Performance_Details)
.addComponent(Tablespaces_Details))
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(182)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(381)
.addComponent(lblPoweredByDsgs, GroupLayout.PREFERRED_SIZE, 185, GroupLayout.PREFERRED_SIZE)))))
.addContainerGap(1161, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblEnterTheDatabase, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE)
.addContainerGap(1754, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(DBUser_Input)
.addComponent(Username, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(48)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(syspass_label, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE)
.addComponent(syspassword, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(58)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(space_user_lable)
.addComponent(Schema, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(45)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(schema_password, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(44)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(Instance, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(44)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(Hostname)
.addComponent(host, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(lblEnterTheDatabase)
.addComponent(Port, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(progressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(selectall))
.addGap(18)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(Exp_Schema_Check)
.addGap(18)
.addComponent(DB_Parameters_Sizing_Details)
.addGap(18)
.addComponent(Redo_Archive_Details)
.addGap(18)
.addComponent(Session_Details)
.addGap(18)
.addComponent(SPM_Performance_Details)
.addGap(18)
.addComponent(Tablespaces_Details))
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(lblPoweredByDsgs)))
.addGap(49)
.addComponent(lblPoweredByDs, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
getContentPane().setLayout(layout);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField4ActionPerformed
/**
* @param args the command line arguments
* @return 
* @return 
* @throws InterruptedException 
*/
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(JFrame_Demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrame_Demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrame_Demo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrame_Demo.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() {
try {
new JFrame_Demo().setVisible(true);
} catch (FontFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JCheckBox Exp_Schema_Check;
private javax.swing.JCheckBox DB_Parameters_Sizing_Details;
private javax.swing.JCheckBox Redo_Archive_Details;
private javax.swing.JCheckBox Session_Details;
private javax.swing.JCheckBox Tablespaces_Details;
private javax.swing.JCheckBox SPM_Performance_Details;
private javax.swing.JLabel DBUser_Input;
private javax.swing.JLabel dbpassword1;
private javax.swing.JLabel space_user_lable;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPasswordField syspassword;
private javax.swing.JPasswordField schema_password;
private javax.swing.JTextField Schema;
private javax.swing.JTextField Username;
private javax.swing.JTextField Instance;
private JTextField host;
private JTextField Port;
HSSFWorkbook workbook = new HSSFWorkbook();
private JLabel lblPoweredByDsgs;
private JCheckBox selectall;
private JProgressBar progressBar;
}

Thank you very much.

答案1

得分: 1

SwingWorker 用于运行长时间的任务。但在这里不需要,所以您不需要使用它。

以下是您想要实现的示例代码:

import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

public class SwingMain {

    SwingMain() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(new TestPanel());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new SwingMain();
    }
}

class TestPanel extends JPanel {

    private final List<JCheckBox> checkBoxes;

    public TestPanel() {

        checkBoxes = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            JCheckBox cb = new JCheckBox();
            checkBoxes.add(cb);
            add(cb);
        }

        JProgressBar pb = new JProgressBar();
        add(pb);

        JButton btn = new JButton("Check");
        btn.addActionListener(evt -> pb.setValue(countCheckedBoxes() * 100 / checkBoxes.size()));
        add(btn);
    }

    private int countCheckedBoxes() {

        int counter = 0;
        for (JCheckBox cb : checkBoxes) {
            if (cb.isSelected()) {
                counter++;
            }
        }
        return counter;
    }

    /* 一个使用流更简洁的版本:
    private int countCheckedBoxes() {
        return (int) checkBoxes.stream().filter(cb -> cb.isSelected()).count();
    }
    */
}

编辑:
如果您需要更新长时间过程的进度,请使用 SwingWorker

import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

public class SwingMain {

    SwingMain() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(new TestPanel());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new SwingMain();
    }
}

class TestPanel extends JPanel {

    private final JProgressBar pb;
    private final JButton btn;

    public TestPanel() {

        pb = new JProgressBar();
        add(pb);

        btn = new JButton("Run long process");
        btn.addActionListener(evt -> new ProgressUpdateTask().execute());
        add(btn);
    }

    class ProgressUpdateTask extends SwingWorker<Void, Integer> {

        @Override
        protected void process(List<Integer> chunks) {
            int i = chunks.get(chunks.size() - 1);
            pb.setValue(i); // The last value in this array is all we care about.
        }

        @Override
        protected Void doInBackground() throws Exception {
            btn.setEnabled(false);
            for (int i = 0; i < 100; i++) {
                Thread.sleep(50); // 模拟长时间过程
                publish(i);
            }
            btn.setEnabled(true);
            return null;
        }
    }
}
英文:

SwingWorker is used for running long tasks. This is not the case here so you do not need one.<br/>
The following is mre <sup>(1)</sup> of what you are trying to achieve:

import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
public class SwingMain {
SwingMain() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(new TestPanel());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new SwingMain();
}
}
class TestPanel extends JPanel {
private final List&lt;JCheckBox&gt; checkBoxes;
public TestPanel() {
checkBoxes = new ArrayList&lt;&gt;();
for (int i=0; i&lt;5; i++){
JCheckBox cb = new JCheckBox();
checkBoxes.add(cb);
add(cb);
}
JProgressBar pb = new JProgressBar();
add(pb);
JButton btn = new JButton(&quot;Check&quot;);
btn.addActionListener(evt -&gt;  pb.setValue(countCheckedBoxes()* 100/checkBoxes.size()));
add(btn);
}
private int countCheckedBoxes() {
int counter = 0;
for(JCheckBox cb : checkBoxes){
if(cb.isSelected()) {
counter++;
}
}
return counter;
}
/* a more concise version using stream: 
private int countCheckedBoxes() {
return (int) checkBoxes.stream().filter(cb-&gt;cb.isSelected()).count();
}
*/
}

EDIT:
If you need to update progress of a long process use SwingWorker:

import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class SwingMain {
SwingMain() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(new TestPanel());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new SwingMain();
}
}
class TestPanel extends JPanel {
private final JProgressBar pb;
private final JButton btn;
public TestPanel() {
pb = new JProgressBar();
add(pb);
btn = new JButton(&quot;Run long process&quot;);
btn.addActionListener(evt -&gt;  new ProgressUpdateTask().execute());
add(btn);
}
class ProgressUpdateTask extends SwingWorker&lt;Void, Integer&gt; {
@Override
protected void process(List&lt;Integer&gt; chunks) {
int i = chunks.get(chunks.size()-1);
pb.setValue(i); // The last value in this array is all we care about.
}
@Override
protected Void doInBackground() throws Exception {
btn.setEnabled(false);
for(int i = 0; i &lt; 100; i++) {
Thread.sleep(50); //simulate long process
publish(i);
}
btn.setEnabled(true);
return null;
}
}
}

<hr>
<sup>(1)</sup> Always consider posting an MRE when asking and answering.

huangapple
  • 本文由 发表于 2020年8月27日 17:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63612798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定