⽤java实现简易推箱⼦代码
package yan04;
import java.awt.Button;
import java.awt.Color;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class MoveBox extends JFrame implements KeyListener,ActionListener {
Label label=new Label("单击⼀个积⽊,然后移动它");
Button b[]=new Button[40];
int x[]=new int[40];
int y[]=new int[40];
int k1=70,k2=70,k3=70,k4=70;
String s="";
public MoveBox() {
super("Move Box");
setLayout(null);
java valueofadd(label);
label.setBounds(0,0,150,30);
for(int i=0;i<40;i++)
{
b[i]=new Button(String.valueOf(i));
if(i%3==0) b[i].d);
if(i%3==1) b[i].setBackground(Color.blue);
if(i%3==2) b[i].llow);
b[i].addKeyListener(this);
b[i].addActionListener(this);
add(b[i]);
if(i%4==0) {
b[i].setBounds(k1,40,30,30);k1=k1+31;
}else if(i%4==1) {
b[i].setBounds(k1,71,30,30);k2=k2+31;
}else if(i%4==2) {
b[i].setBounds(k1,102,30,30);k2=k3+31;
}else if(i%4==3) {
b[i].setBounds(k1,133,30,30);k2=k4+31;
}
}
for(int i=0;i<40;i++)
{
x[i]=b[i].getBounds().x;
y[i]=b[i].getBounds().y;
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,400);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0;i<40;i++)
{
Source()==b[i])
s=b[i].getLabel();
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
KeyCode()==KeyEvent.VK_UP) {
for(int i=0;i<=39;i++)
{
if(s.equals(String.valueOf(i))) {
y[i]=y[i]-2;
if(y[i]<=0) y[i]=0;
b[i].setLocation(x[i],y[i]);
}
}
}else KeyCode()==KeyEvent.VK_DOWN) {
for(int i=0;i<=39;i++)
{
if(s.equals(String.valueOf(i))) {
y[i]=y[i]+2;
if(y[i]>=280) y[i]=280;
b[i].setLocation(x[i],y[i]);
}
}
}else KeyCode()==KeyEvent.VK_LEFT) { for(int i=0;i<=39;i++)
{
if(s.equals(String.valueOf(i)))
{
x[i]=x[i]-2;
if(x[i]<=0) x[i]=0;
b[i].setLocation(x[i],y[i]);
}
}
}
}
@Override
public void keyReleased(KeyEvent e) {
}
public static void main(String args[]) {
new MoveBox();
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论