据我了解所有情况,我需要为算法,进度条执行单独的线程,并保留对话框的主线程(让他有机会响应用户操作)。所以我尝试实现这一点,并得到以下内容:
public class ScheduleDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private static Data data;
private static GeneticEngine geneticEngine;
private static Schedule schedule;
private static JProgressBar progressBar;
private static JLabel statusLabel;
public static void showProgress() {
try {
ScheduleDialog dialog = new ScheduleDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
startScheduleComposing();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void startScheduleComposing() {
BackGroundWorker backGroundWorker = new BackGroundWorker();
GeneticEngineWorker geneticEngineWorker = new GeneticEngineWorker();
new Thread(geneticEngineWorker).start();
new Thread(backGroundWorker).start();
}
private ScheduleDialog() {
this.data = Data.getInstance();
setTitle("");
setModal(true);
setBounds(100, 100, 405, 150);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension dialogSize = getSize();
setLocation((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new GridLayout(0, 1, 0, 0));
{
progressBar = new JProgressBar();
progressBar.setBackground(Color.RED);
contentPanel.add(progressBar);
}
{
statusLabel = new JLabel("");
contentPanel.add(statusLabel);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("Прервать");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
protected static class BackGroundWorker implements Runnable {
@Override
public void run() {
while(true){
int barValue = 100 - (geneticEngine.getCurrentBestFitness() / geneticEngine.getInitialFitness());
progressBar.setValue(barValue);
progressBar.repaint();
statusLabel.setText(String.valueOf(geneticEngine.getCurrentBestFitness()));
statusLabel.repaint();
try{
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
protected static class GeneticEngineWorker implements Runnable{
@Override
public void run() {
geneticEngine = new GeneticEngine(data);
schedule = geneticEngine.GeneticAlgorithm();
}
}
}
似乎new Thread(geneticEngineWorker).start();
正在运行,但进度条没有任何反应。我想这部分代码:
private static void startScheduleComposing() {
BackGroundWorker backGroundWorker = new BackGroundWorker();
GeneticEngineWorker geneticEngineWorker = new GeneticEngineWorker();
new Thread(geneticEngineWorker).start();
new Thread(backGroundWorker).start();
}
我们只有在new Thread(backGroundWorker).start();
停止后才会执行new Thread(geneticEngineWorker).start();
所以,如果我是对的,请告诉我如何重新组织代码来完成工作,如果我错了,你可以指出我的错误吗?
提前感谢大家!
ADDITION
我对它进行了调试,正如我想的那样,backGroundWorker仅在geneEngineWorker结束或用户关闭对话框后开始工作(在这种情况下例外);
答案 0 :(得分:4)
是的,使用
有两种基本方法 SwingWorker,需要有关Java Essential Classes
inc的最深入了解。 Generics
也是
和
Runnable#Thread
只需将输出包装到GUI invokeLater()
关于Runnable#Thread
中所有想法JProgressBar
,JTable
所需的特殊工作的简单示例,这意味着代码行model.setValueAt(value, row, column);
应该包含在invokeLater
中,但在其他方面setText()
被声明为线程安全,我建议在所有情况下将其包装到invokeLater
import java.awt.Component;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class TableWithProgressBars {
private static final int maximum = 100;
public void createGUI() {
final JFrame frame = new JFrame("Progressing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Integer[] oneRow = {0, 0, 0, 0};
String[] headers = {"One", "Two", "Three", "Four"};
Integer[][] data = {oneRow, oneRow, oneRow, oneRow, oneRow,};
final DefaultTableModel model = new DefaultTableModel(data, headers);
final JTable table = new JTable(model);
table.setDefaultRenderer(Object.class, new ProgressRenderer(0, maximum));
table.setPreferredScrollableViewportSize(table.getPreferredSize());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Thread(new Runnable() {
@Override
public void run() {
Object waiter = new Object();
synchronized (waiter) {
int rows = model.getRowCount();
int columns = model.getColumnCount();
Random random = new Random(System.currentTimeMillis());
boolean done = false;
while (!done) {
int row = random.nextInt(rows);
int column = random.nextInt(columns);
Integer value = (Integer) model.getValueAt(row, column);
value++;
if (value <= maximum) {
model.setValueAt(value, row, column);
try {
waiter.wait(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
done = true;
for (row = 0; row < rows; row++) {
for (column = 0; column < columns; column++) {
if (!model.getValueAt(row, column).equals(maximum)) {
done = false;
break;
}
}
if (!done) {
break;
}
}
}
frame.setTitle("All work done");
}
}
}).start();
}
public static class ProgressRenderer extends JProgressBar implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public ProgressRenderer(int min, int max) {
super(min, max);
this.setStringPainted(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
this.setValue((Integer) value);
return this;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TableWithProgressBars().createGUI();
}
});
}
}