用线程控制图片的交替显示
import java.awt.*;import java.awt.event.*;
import javax.swing.*;
public class game5 extends JFrame {
static JLabel label;
String path = "E:/pic/";
static Icon p1, p2, p3;
static Boolean start;
public game5() {
this.setTitle("石头剪子布");
this.setSize(600, 300);
this.setVisible(true);
Container c = this.getContentPane();
c.setLayout(new GridLayout(1, 3));
JButton b1 = new JButton("start");
JButton b2 = new JButton("over");
label = new JLabel();
c.add(b1);
c.add(b2);
c.add(label);
p1 = new ImageIcon(path + "g.gif");
p2 = new ImageIcon(path + "o.gif");
p3 = new ImageIcon(path + "p.gif");
b1.addActionListener(new start(""));
b2.addActionListener(new over());
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
class start extends Thread implements ActionListener {
// 添加构造函数
public start(String name) {
super(name);
}
public void actionPerformed(ActionEvent e) {
game5.start = true;
// 问题中这里创建的三个线程是Thread空对象
Thread t1 = new start("t1");
Thread t2 = new start("t2");
Thread t3 = new start("t3");
t1.start();
t2.start();
t3.start();
}
synchronized void set() {
while (start) {
// 使用equals比较对象
if (this.getName().equals("t1")) {
game5.label.setIcon(p1);
}
if (this.getName().equals("t2")) {
game5.label.setIcon(p2);
}
if (this.getName().equals("t3")) {
game5.label.setIcon(p3);
}
}
}
public void run() {
set();
}
}
class over implements ActionListener {
public void actionPerformed(ActionEvent e) {
game5.start = false;
}
}
public static void main(String args[]) {
new game5();
}
}
为什么在程序运行后,图片交替显示的速度越来越慢,最后好长时间才更换一张,甚至不动了,窗口也关闭不了了 线程 swing
补充:Java , Java SE