swing中线程

来源:互联网 发布:数据库null底层原理 编辑:程序博客网 时间:2024/05/20 20:05
package org.chapter.thread;


import java.awt.*;


import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;


import javax.swing.JFrame;


public class Bounce {
public static void main(String[] args) {
EventQueue.invokeLater(new  Runnable() {

@Override
public void run() {

new BounceFrame();
}
});


}


}
 class BounceFrame extends JFrame{
 
private Ballcomponent comp;
public static final int STEPS=1000;
public static final int DELAY=3;
 
 
 
 
public BounceFrame() {
//得到屏幕的方位
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
this.setBounds((dim.width-500)/2, (dim.height-500)/2, 500, 500);
this.setVisible(true);
//设置 默认退出时候的状态
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Bounce");
 
comp= new Ballcomponent();
this.add(comp,BorderLayout.CENTER);
JPanel buttonPanel=new JPanel();

addButton(buttonPanel, "start", new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
addBall();
}
});


addButton(buttonPanel, "close", new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
this.add(buttonPanel,BorderLayout.SOUTH);
 
}
 
 
 
public void  addButton(Container c,String  tittle ,ActionListener listener){
JButton button=new JButton(tittle);
c.add(button);
button.addActionListener(listener);
}
 
public void addBall(){
try {
Ball ball=new Ball();
comp.add(ball);
for (int i = 0; i <=STEPS; i++) {
ball.move(comp.getBounds());
comp.paint(comp.getGraphics());
Thread.sleep(DELAY);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
 
 
 
 }
 
 
 class Ballcomponent extends JPanel{
 
private List<Ball> balls=new ArrayList<Ball>();
public void add(Ball b){
balls.add(b);
}
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
for (Ball b : balls) {
g2.fill(b.getShape());
}
}
 }
 
 class Ball{
 
 
private static final int XSIZE=15;
private static final int YSIZE=15;
private double x=0;
private double y=0;
private double dx=1;
private double dy=1;
public void move(Rectangle2D bounds){
x+=dx;
y+=dy;
if(x<bounds.getMinX()){
x=bounds.getMinX();
dx=-dx;
}
if(x+XSIZE>=bounds.getMaxX()){
x=bounds.getMaxX()-XSIZE;
dx=-dx;
}
if(y<bounds.getMinY()){
y=bounds.getMaxY()-YSIZE;
dy=-dy;
}
 
}
public Ellipse2D getShape(){
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
}
原创粉丝点击