java timer 动画,Java中使用Timer 这个类来完成Swing的动画效果。

在网上找了好久都没有找到包含整个源代码的Swing动画,特别是淡入淡出效果,现在先上传个简单的动画供大家参考

package com.sbt.common.client.utils;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.Graphics;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.Timer;

/**

* 演示如何使用Timer 这个类来完成Swing的动画效果。

* @author zcl

*/

public class TestWindow extends JPanel {

private final int panelWidth = 300, panelHeight = 200;

private final int DELAY = 10, IMAGE_SIZE = 35;

private Timer timer;

private JButton topButton;

private int x, y, moveX, moveY;

/**

* 面板构造函数,初始化面板。包括Timer 的场景。

*/

public TestWindow() {

timer = new Timer(DELAY, new ReboundListener());

this.setLayout(new FlowLayout(FlowLayout.LEFT));

topButton = new JButton("top");

// topButton.setPreferredSize(new Dimension(20, 20));

x = 0;

y = 40;

moveX = moveY = 3;

setBackground(Color.WHITE);

this.setBorder(BorderFactory.createLineBorder(Color.GREEN));

JButton button = new JButton("click");

button.addMouseListener(getClickListener());

this.add(button);

}

private AsynMouseEventListener clickListener;

private AsynMouseEventListener getClickListener(){

if(clickListener == null){

clickListener = new AsynMouseEventListener() {

@Override

public boolean prepareAction(MouseEvent e){

if(e.getButton() == MouseEvent.BUTTON1){

timer.start();

}else{

timer.stop();

}

return false;

}

};

}

return clickListener;

}

/**

* 绘出图像在面板中的位置。

* @param page

*/

@Override

public void paintComponent(Graphics page) {

super.paintComponent(page);

topButton.paint(page);

}

//Swing 动画,不断的更新图像的位置,已达到动画的效果。

private class ReboundListener implements ActionListener {

@Override

public void actionPerformed(ActionEvent e) {

x += moveX;

y += moveY;

topButton.setBounds(0, 0, 100, y);

if (x <= 0 || x >= panelWidth - IMAGE_SIZE) {

moveX = moveX * (-1);

}

if (y <= 0 || y >= panelHeight - IMAGE_SIZE) {

moveY = moveY * (-1);

// moveY =0;

}

repaint();

}

}

public static void main(String[] args) {

JFrame frame = new JFrame("JUST SOSO");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(new TestWindow());

frame.setSize(300, 300);

frame.setLocation(400, 400);

frame.setVisible(true);

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值