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);
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值