[英]How to fix JProgressBar using SwingWorker?
I wrote the following code that I thought would work, I wanted to open a new JFrame on a button click that shows a progress bar that gets updated: 我写了以下我认为可行的代码,我想在按钮上单击打开一个新的JFrame,其中显示了一个更新的进度条:
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int numOfRows = getRows();//function that returns number of rows
int numOfColumns = getColumns();//function that returns number of columns
String myquery = "select * from foo_table";
rs = null;
try {
rs = st.executeQuery(myquery);
// extract column information
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
columnData = new ArrayList<String>(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnData.add(rsmd.getColumnName(i));
}
// sql result data
table_ResQues.setModel(new ListTableModel(Collections.<List<Object>>emptyList(), Collections.<String>emptyList()));
rowData = new ArrayList<List<Object>>();
final JFrame progFrame = new JFrame("Processing...");
JPanel mainPPanel = new JPanel(new BorderLayout());
JProgressBar progBar = new JProgressBar(0,100);
progFrame.setBounds(850,300,400,100);
progFrame.setVisible(true);
progBar = new JProgressBar(0,100);
mainPPanel.add(progBar, BorderLayout.NORTH);
progFrame.add(mainPPanel);
progFrame.setVisible(true);
int countRows = 0;
int area = numOfRows*numOfColumns;
int totalTime = area % 200000;
int xPerSec = totalTime/100;
while (rs.next()) {
row = new ArrayList<Object>(columnCount);
for (int i = 0; i < columnCount; i++) {
row.add(rs.getObject(i + 1));
}
rowData.add(row);
countRows++;
if(countRows*numOfColumns == 200000){
progBar.setValue(xPerSec++);
countRows = 0;
}
}
table_ResQues.setModel(new ListTableModel(rowData, columnData));
}catch (SQLException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
});
But when googling my problem I realized it is a threading issue, and I never had any experience with threading or SwingWorker, can anyone help me implement what I want using SwingWorker? 但是在搜索我的问题时,我意识到这是一个线程问题,而且我从没有使用线程或SwingWorker的经验,有人可以帮助我使用SwingWorker实现我想要的东西吗? Should my while-loop be the one that's running in the background?
我的while循环是否应该在后台运行? should it be a class by itself?
它本身应该是一个阶级吗? Sorry, i'm really confused.
对不起,我真的很困惑。
I have solved it by creating a new class that extends SwingWorker and overriding it's methods. 我已经通过创建一个扩展SwingWorker并覆盖其方法的新类解决了该问题。 Thanks for the help in the comments.
感谢您在评论中的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.