//主函数代码
import cn.test.ui.BulletFrame;
public class MainApp {
public static void main(String[] args) {
BulletFrame frame = new BulletFrame();
frame.setVisible(true);
}
}
//创建子弹模拟界面
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BulletFrame extends JFrame {
static JButton button1;
static JButton button2;
public BulletFrame() {
init();
addOtherCompont();
}
private void addOtherCompont() {
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.BLACK);
button1 = new JButton();
button2 = new JButton();
button1.setBackground(Color.WHITE);
button2.setBackground(Color.WHITE);
button1.setBounds(10,150,20,10);
button2.setBounds(460,150,20,10);
Bullet bullet1 = new Bullet(button1);
Bullet bullet2 = new Bullet(button2);
bullet1.setName("bullet1");
bullet2.setName("bullet2");
bullet1.start();
bullet2.start();
panel.add(button1);
panel.add(button2);
this.add(panel);
}
private void init() {
// 标题
this.setTitle("Bullet Simulate");
// 大小
this.setSize(500, 400);
// 固定位置
this.setLocation(400, 150);
// 固定大小
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
//添加判断位置进行执行显示碰撞
package cn.test.ui;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class Bullet extends Thread {
int sleepTime = 150;
private JButton bt1;
private JButton bt2;
int i, j;
Bullet(JButton bt) {
this.bt1 = bt;
this.bt2 = bt;
}
public void run() {
for (i = 10, j = 460; i <= 460; i++, j--) {
if (Thread.currentThread().getName().equals("bullet1")) {
if(i==226) {
JOptionPane.showMessageDialog(null, "碰撞!");
return;
}
bt1.setBounds(i++, 150, 20, 10);
try {
sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (Thread.currentThread().getName().equals("bullet2")) {
if(j==242) return;
bt2.setBounds(j--, 150, 20, 10);
try {
sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
体会
因为之前在主界面中进行判断的时候,必须要进行for循环,以此才能得到每次的子弹的位置,然而,代码却因此出现了一些bug,所以,我用了一些比较投机取巧的方法,希望大家不要太在意