前端之家收集整理的这篇文章主要介绍了
单一线程规则,不要在自己的线程中触摸swing组件,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
class SwingThreadFrame extends JFrame {
public SwingThreadFrame() {
setTitle("Swing Thread");
final JComboBox<Integer> combo = new JComboBox<Integer>();
combo.insertItemAt(Integer.MAX_VALUE,0);
combo.setPrototypeDisplayValue(combo.getItemAt(0));
combo.setSelectedIndex(0);
JPanel panel = new JPanel();
JButton goodButton = new JButton("Good");
goodButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
new Thread(new GoodWorkerRunnable(combo)).start();
}
});
panel.add(goodButton);
JButton badButton = new JButton("Bad");
badButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
new Thread(new BadWorkerRunnable(combo)).start();
}
});
panel.add(badButton);
panel.add(combo);
add(panel);
pack();
}
}
class GoodWorkerRunnable implements Runnable {
public GoodWorkerRunnable(JComboBox<Integer> combo) {
this.combo = combo;
generator = new Random();
}
@Override
public void run() {
try {
while(true) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
int i = Math.abs(generator.nextInt());
if(i % 2 == 0) {
combo.insertItemAt(i,0);
} else if(combo.getItemCount() > 0) {
combo.removeItemAt(i % combo.getItemCount());
}
}
});
Thread.sleep(1);
}
} catch (InterruptedException e) {
}
}
private JComboBox<Integer> combo;
private Random generator;
}
class BadWorkerRunnable implements Runnable {
public BadWorkerRunnable(JComboBox<Integer> combo) {
this.combo = combo;
generator = new Random();
}
@Override
public void run() {
try {
while(true) {
int i = Math.abs(generator.nextInt());
if(i % 2 == 0) {
combo.insertItemAt(i,0);
} else if(combo.getItemCount() > 0) {
combo.removeItemAt(i % combo.getItemCount());
}
Thread.sleep(1);
}
} catch (InterruptedException e) {
}
}
private JComboBox<Integer> combo;
private Random generator;
}
原文链接:https://www.f2er.com/javaschema/286769.html