JAVA 实现漂浮效果

来源:互联网 发布:怎么删除淘宝上的好评 编辑:程序博客网 时间:2024/05/18 02:38
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(newGridLayout(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);
 }
}
原创粉丝点击