首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

线程兑现弹球

2013-08-10 
线程实现弹球import java.awt.FlowLayoutimport java.awt.event.ActionEventimport java.awt.event.Acti

线程实现弹球
import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;public class jframe extends JFrame {static jframe jf;public static void main(String[] args) {jf = new jframe();jf.initUI();}public void initUI() {this.setSize(600, 500);this.setDefaultCloseOperation(3);this.setLayout(new FlowLayout());this.setVisible(true);JButton btn = new JButton("开始");btn.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {thread td = new thread(jf);td.start();}});this.add(btn);}}import java.awt.Color;import java.awt.Graphics;import javax.swing.JFrame;public class thread extends Thread {JFrame jf;int X = 0; // X坐标int Y = 0; // Y坐标int moveX = 2; // X轴位移int moveY = 3; // Y轴位移int width;int height;Graphics g;public thread(JFrame jf) {this.jf = jf;}public void run() {init();while (true) {try {Thread.sleep(10);// 线程暂停10毫秒,减少CPU使用率} catch (Exception E) {}g.setColor(jf.getBackground());g.fillRect(X, Y, width, height);X = X + moveX;// 重新计算X、Y坐标Y = Y + moveY;// 碰到边界时改变递增值造成反弹效果if (X >= (width - 30)) {X = width - 30;moveX = -moveX;}if (X <= 0) {X = 0;moveX = -moveX;}if (Y >= (height - 30)) {Y = height - 30;moveY = -moveY;}if (Y <= 0) {Y = 0;moveY = -moveY;}//g.setColor(Color.WHITE);//g.fillRect(X, Y, 30, 30);g.setColor(Color.BLACK);g.fillOval(X, Y, 30, 30);}}public void init() {g = jf.getGraphics();width = jf.getWidth();height = jf.getHeight();}}

?

热点排行