代碼還可以優(yōu)化,你自己修改吧!代碼有點小問題,運行后,按鈕2會全屏,你按鍵盤方向鍵就會好了!這個問題你自己想辦法修改吧。不過可以實現(xiàn)你要的功能。
public class PaintovalFrame extends JFrame {
private static JButton objT1;
private static JButton objT2;
public PaintovalFrame() {
setSize(500,500);
objT1 = new JButton("1");
objT1.setBounds(120, 40, 50, 40);
add(objT1);
objT2 = new JButton("2");
objT2.setBounds(20, 40, 50, 40);
add(objT2);
objT1.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==e.VK_UP){
objT1.setBounds(objT1.getX(), objT1.getY() - 10, 50, 40);
} else if(e.getKeyCode()==e.VK_DOWN){
objT1.setBounds(objT1.getX(), objT1.getY() + 10, 50, 40);
} else if(e.getKeyCode()==e.VK_LEFT){
objT1.setBounds(objT1.getX() - 10, objT1.getY(), 50, 40);
} else if(e.getKeyCode()==e.VK_RIGHT){
objT1.setBounds(objT1.getX() + 10, objT1.getY(), 50, 40);
}
}
});
objT2.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==e.VK_UP){
objT2.setBounds(objT2.getX(), objT2.getY() - 10, 50, 40);
} else if(e.getKeyCode()==e.VK_DOWN){
objT2.setBounds(objT2.getX(), objT2.getY() + 10, 50, 40);
} else if(e.getKeyCode()==e.VK_LEFT){
objT2.setBounds(objT2.getX() - 10, objT2.getY(), 50, 40);
} else if(e.getKeyCode()==e.VK_RIGHT){
objT2.setBounds(objT2.getX() + 10, objT2.getY(), 50, 40);
}
}
});
}
public static void main(String[] args) {
PaintovalFrame objPane = new PaintovalFrame();
objPane.setVisible(true);
}
}