我编写了以下代码,我认为它可以工作,我想在按钮点击上打开一个新的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();
}
});
但是在搜索我的问题时,我意识到这是一个线程问题,而且我从未有过使用线程或SwingWorker的经验,任何人都可以帮助我使用SwingWorker实现我想要的东西吗?我的while循环应该是在后台运行吗?它本身应该是一个类吗?对不起,我真的很困惑。
答案 0 :(得分:0)
我通过创建一个扩展SwingWorker并覆盖它的方法的新类来解决它。感谢评论中的帮助。