我是菜鸟我怕谁,有胆无谋才做贼。
天天练习手不生,愿识路上有识君。
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
/**
*
* @author Administrator 跳动的小球
* 要求:点击Srart从窗体左上角创建一个小球,小球按45度角向下运动,当碰到窗体边缘弹回,要求经过一定时间小球停止运动并消失
* 。注:只要是点击Start就创建小球并运动,可创建多个小球。(体会多线程并发的概念)
*/
public class Ball extends Thread{
private JPanel panel;
private static final int width=10;
private static final int height=10;
private int x;
private int y;
private int dx=2;
private int dy=2;
public Ball(JPanel p){
panel=p;
}
public void draw(){
Graphics g=panel.getGraphics();
g.fillOval(x, y, width, height);
g.dispose();
}
public void move(){
if (!panel.isVisible()) return;
Graphics g=panel.getGraphics();
g.setXORMode(panel.getBackground());
g.fillOval(x, y, width, height);
x+=dx;
y+=dy;
Dimension d=panel.getSize();
if(x<0){
x=0;
dx=-dx;
}
if(x+width>=d.width){
x=d.width -width;
dx=-dx;
}
if(y<0){
y=0;
dy=-dy;
}
if(y+height>=d.height){
y=d.height -height;
dy=-dy;
}
g.fillOval(x, y, width, height);
g.dispose();
}
public void run() {
draw();
for(int i=0;i<1000;i++ ){
move();
try {
sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Start extends JFrame{
private Ball ball;
private JPanel panel;
private JButton start;
private JButton close;
public void init(){
this.setTitle("跳动的小球");
panel=new JPanel();
panel.setBounds(new Rectangle(0, 0 ,390, 265));
start=new JButton("start");
start.setBounds(new Rectangle(100,240,80, 30));
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ball=new Ball(panel);
ball.start();
}
});
close=new JButton("close");
close.setBounds(new Rectangle(210,240,80, 30));
panel.setLayout(null);
panel.add(start);
panel.add(close);
this.setLayout(null);
this.add(panel);
this.setBounds(30, 30, 400, 300);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String args[]){
new Start().init();
}
}