JLabel碰撞

import java.awt.*;
import javax.swing.*;
class Crash extends Frame implements Runnable
{
 Icon l1,l2;
 JLabel j1,j2;
 Thread t1,t2;
 int x1=100,y1=200,x2=200,y2=100,b1=0,b2=0,b3=0,b4=0;
 Crash(String s)
 {
  super(s);
  setLayout(null);
  l1 = new ImageIcon("bomb.gif");
  l2 = new ImageIcon("baozi.jpg");
  j1 = new JLabel(l1);
  j2 = new JLabel(l2);
  add(j1);
  add(j2);
  j1.setBounds(x1,y1,50,50);
  j2.setBounds(x2,y2,50,50);
  t1 = new Thread(this);
  t2 = new Thread(this);
  t1.start();
  t2.start();
  setBounds(100,100,600,450);
  setVisible(true);
 }
 public void run()
 {
  while(true)
  {
   if(Thread.currentThread() == t1)
   {
    
    if(x1>550)
    {
     b1++;System.out.println("b1="+b1);
    }
    else if(x1 < 0)
    {
     b1--;System.out.println("b1="+b1);
    }
    else if(y1 > 400)
    {
     b2++;System.out.println("b2="+b2);
    }
    else if(y1 < 10)
    {
     b2--;System.out.println("b2="+b2);
    }
    if(b1%2==1)
    {
     x1 -= 5; System.out.println("x1="+x1);
    }
    else
    {
     x1 += 5; System.out.println("x1="+x1);
    }
    if(b2%2==1)
    {
     y1 -= 5; System.out.println("y1="+y1);
    }
    else
    {
     y1 += 5; System.out.println("y1="+y1);
    }
    j1.setBounds(x1,y1,50,50);
    try
    {
     t1.sleep(30);
    }
    catch(InterruptedException e)
    {
    }
   }
   if(Thread.currentThread() == t2)
   {
    if(x2 > 550)
    {
     b3++;System.out.println("b3="+b3);
    }
    else if(x2 < 0)
    {
     b3--;System.out.println("b3="+b3);
    }
    else if(y2 > 400)
    {
     b4++;System.out.println("b4="+b4);
    }
    else if(y2 < 10)
    {
     b4--;System.out.println("b4="+b4);
    }
    if(b3%2==1)
    {
     x2 -= 5; System.out.println("x2="+x2);
    }
    else
    {
     x2 += 5; System.out.println("x2="+x2);
    }
    if(b4%2==1)
    {
     y2 -= 5; System.out.println("y2="+y2);
    }
    else
    {
     y2 += 5; System.out.println("y2="+y2);
    }
    j2.setBounds(x2,y2,50,50);
    try
    {
     t2.sleep(30);
    }
    
    catch(InterruptedException e)
    {
    }
   }
   Rectangle rect = j1.getBounds();
   if(rect.intersects(j2.getBounds()))
   {
    b1++;b2++;b3++;b4++;
   }
  }
 }
 public static void main(String args[])
 {
  Crash c = new Crash("碰撞");
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值