//显示一个圆,通过点击开始和停止按钮来运行动画!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Checkers extends JFrame implements ActionListener{
CheckersPanel checkers = new CheckersPanel();
JButton startButton = new JButton("Strat");
JButton stopButton = new JButton("Stop");
public Checkers(){
super("Checkers");
setBounds(210,170,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
BorderLayout border = new BorderLayout();//布局管理
pane.setLayout(border);
pane.add(checkers,"Center");
JPanel buttonPanel = new JPanel();//创建一个按钮面板 ,用于安放按钮
startButton.addActionListener(this);//添加按钮事件监听
buttonPanel.add(startButton);
stopButton.addActionListener(this);
stopButton.setEnabled(false);//默认情况下使停止按钮为无效
buttonPanel.add(stopButton);
pane.add(buttonPanel,"South");
setContentPane(pane);
setVisible(true);
}
public void actionPerformed(ActionEvent evt){
if(evt.getSource()== startButton){//如果点击的是开始按钮,则会进行如下动作
checkers.playAnimation();
startButton.setEnabled(false);
stopButton.setEnabled(true);
}else{
checkers.stopAnimation();
startButton.setEnabled(true);
stopButton.setEnabled(false);
}
}
public static void main(String[] arg){
Checkers ck = new Checkers();
}
}
class CheckersPanel extends JPanel implements Runnable{
private Thread runner;
int xPos = 5 ;
int xMove = 4;
void playAnimation(){//开始按钮方法
if (runner == null);{
runner = new Thread(this);
runner.start();
}
}
void stopAnimation(){//停止按钮方法
if(runner != null);{
runner = null;
}
}
public void run(){//使用线程的方法来运行动画
Thread thisThread = Thread.currentThread();
while (runner == thisThread){
xPos += xMove;
if((xPos > 105) | (xPos < 5))
xMove *= -1;
repaint();
try{
Thread.sleep(100);
}catch (InterruptedException e){}
}
}
public void paintComponent(Graphics comp ){
Graphics2D comp2D = (Graphics2D)comp;
comp2D.setColor(Color.black);
comp2D.fillRect(0, 0, 100, 100);
comp2D.setColor(Color.white);
comp2D.fillRect(100, 0, 100, 100);
comp2D.setColor(Color.red);
comp2D.fillOval(xPos, 5, 90, 90);
}
}