//显示一个圆,通过点击开始和停止按钮来运行动画!

//显示一个圆,通过点击开始和停止按钮来运行动画!
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);
  }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值