JAVA 实现漂浮效果
package Rong;
import java.awt.Toolkit;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.Timer;
public class FlyFly extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton jb = new JButton();
private Timer tm;
// -----最大点击次数,消失,必须大于或等于1
private static int hp = 1;
// -----最大坐标
private static int W;
private static int H;
// -----当前坐标
private static int xp;
private static int yp;
// -----当前移动步径
private static int xstep = 3;
private static int ystep = 3;
// -----最大移动步径(随机范围,可以设置)
private static int maxxstep = 19;
private static int maxystep = 17;
public FlyFly(int w, int h) {
W = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() - w;
H = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() - h;
System.out.println(W + ":" + H);
this.setSize(w, h);
xp = W / 2;
yp = H / 2;
this.setLocation(xp, yp);
this.setAlwaysOnTop(true); //窗体总在最前面
this.setResizable(false); //窗体不能改变大小
this.setUndecorated(true); //窗体不要边框
this.getContentPane().setLayout(new GridLayout(1, 1));
this.getContentPane().add(jb);
jb.setIcon(new ImageIcon("D:/al.jpg")); //设置JButton的图片效果
jb.addActionListener(this); //这个不能忘记,挂载ActionListener接口。
tm = new Timer(100, this); //Timer是需要依附在一个实现了ActionListener接口的对象上。(单位毫秒,可以设置)
tm.start(); //Timer需要打开
this.setVisible(true);
}
public void changeDirection() {
// 如果到达边沿要转弯
if ((xp <= 0 && xstep < 0) || (xp >= W && xstep > 0)) {
xstep = -xstep;
}
if ((yp <= 0 && ystep < 0) || (yp >= H && ystep > 0)) {
ystep = -ystep;
}
this.setLocation(xp, yp); // 位置重新设置
}
public void actionPerformed(ActionEvent e) {
// 坐标按照当前状态移动
xp += xstep;
yp += ystep;
if (e.getSource() == jb) { // 点击造成随机生成移动状态
hp--;
xp = (int) System.currentTimeMillis() % W;
yp = (int) System.currentTimeMillis() % H;
xstep = (int) System.currentTimeMillis() % (2 * maxxstep + 1)
- maxxstep;
ystep = (int) System.currentTimeMillis() % (2 * maxystep + 1)
- maxystep;
}
changeDirection(); // 刷新显示状态
if (hp <= 0) {
System.exit(0);
}
}
public static void main(String[] _s) {
FlyFly ff = new FlyFly(200, 200);
}
}
原作者:ios基地
原文出处:CSDN博客
原文链接:https://blog.csdn.net/u012202641/article/details/11896647?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160464154519195264713520%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=160464154519195264713520&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~sobaiduend~default-4-11896647.pc_v1_rank_blog_v1&utm_term=java&spm=1018.2118.3001.4450