同一个Thread不能start两次
这样改下
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class MoveBall02 extends JFrame {
private JButton jbtu = null;
private Ball02 ball = null;
Thread t = null;
public static void main(String[] args) {
new Test();
}
public Test() {
this.setTitle("移动的小球");
this.setSize(600, 500);
this.setLocation(100, 100);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
ball = new Ball02(40, 40);
this.add(ball);
t = new Thread(ball);
jbtu = new JButton("点击移动小球");
this.add(jbtu, BorderLayout.SOUTH);
jbtu.addActionListener(new MyActionListener());
this.setVisible(true);
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtu) {
// 响应鼠标点击事件
if (!t.isAlive()) {
t = new Thread(ball);
t.start();
}
}
}
}
}
@SuppressWarnings("serial")
class Ball02 extends JPanel implements Runnable {
private int x, y;
public Ball02(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillOval(x, y, 40, 40);
}
public void run() {
try {
for (int i = 0; i < 20; i++) {
x = y += 3;
this.repaint();
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public final boolean isAlive()
测试线程是否处于活动状态。如果线程已经启动且尚未终止,则为活动状态。
返回:
如果该线程处于活动状态,则返回 true;否则返回 false。
你还没start 就判断状态,貌似不对哦