您的位置:首页 > 其它

一個小小的移動(利用Timer及TimerTask)

2006-04-11 11:23 211 查看
import java.awt.Dimension;

import java.awt.Rectangle;

import java.util.Date;
import java.util.Timer;

import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Frame1
extends JFrame
{
private JButton jButton1 = new JButton();
//生成一個定時器
Timer moveTimer = new Timer();
int x;
int y;
int frameLeft;
int frameRight;
public Frame1()
{
try
{
jbInit();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x=jButton1.getX();
y=jButton1.getY();
frameLeft=this.getX()+this.getWidth();
frameRight=this.getY()+this.getHeight();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void move()
{
Date date=new Date(System.currentTimeMillis()+1000);
//使用內部類執行
moveTimer.schedule(new TimerTask()
{
public void run()
{
x+=40;
System.out.println("X:"+x);
System.out.println("frameLeft:"+frameLeft);
//如果此時已經到了最右邊,那就從左邊開始循環
if(x>=frameLeft)
{
//x=frameX-jButton1.WIDTH;
x=frameLeft-x;
}
jButton1.setLocation(x,y);
}
},date,1000);
}
private void jbInit()
throws Exception
{
this.getContentPane().setLayout(null);
this.setSize(new Dimension(400, 300));
jButton1.setText("jButton1");
jButton1.setBounds(new Rectangle(70, 50, 95, 45));
this.getContentPane().add(jButton1, null);
}
public static void main(String[] arg)
{
Frame1 frame=new Frame1();
frame.setVisible(true);
frame.move();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: