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

本文介绍了一个使用Java Swing创建的简单示例程序,该程序通过定义一个定时任务来改变按钮的位置,使按钮能够在窗口内左右移动。通过这个例子,读者可以了解如何在Java中利用Swing库创建GUI组件,并掌握如何运用Timer类实现定时操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值