上图之后我明白你的意思了。
你是想移动JButton
这简单,把窗体布局设置为空。然后就可以设置JButton的坐标了。
下面给出控制按钮移动的代码。至于你那个游戏我没玩过,不知道咋整。
import java.awt.event.*;
import javax.swing.*;
/**
*实现控制按钮移动
* @author gust
*/
public class TFrame extends JFrame implements ActionListener{
JButton bt1 ,bt2,bt3= null;
public TFrame(){
init();
}
private void init(){
this.setLayout(null);//将布局设置为空
bt1 = new JButton("测试按钮");
bt1.addActionListener(this);
bt1.setBounds(100,100,90,50);
bt2 = new JButton("上移");
bt2.addActionListener(this);
bt2.setBounds(200,100,90,50);
bt3 = new JButton("下移");
bt3.addActionListener(this);
bt3.setBounds(200,180,90,50);
this.add(bt1);
this.add(bt2);
this.add(bt3);
this.setSize(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null); //居中显示
this.setResizable(false);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==bt1){
JOptionPane.showMessageDialog(this, "测试按钮按下");
}else if(e.getSource()==bt2){
bt1.setBounds(bt1.getX(), bt1.getY()-10, 90, 50);
}else if(e.getSource()==bt3){
bt1.setBounds(bt1.getX(), bt1.getY()+10, 90, 50);
}
}
public static void main(String args[]){
new TFrame();
}
}