使用鍵盤方向控制按鈕移動

package result;

import javax.security.auth.x500.X500Principal;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class F8 extends JFrame implements KeyListener {
JButton b[] = new JButton[3];
// 定義按鈕組件數組
int x, y;
public F8() {
setSize(300, 300);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int i = 0; i < b.length; i++) {
b[i] = new JButton("" + i);
b[i].setBackground(Color.red);
b[i].setForeground(Color.yellow);
b[i].addKeyListener(this);
add(b[i]);
}
validate();
}

public void keyPressed(KeyEvent e) {
JButton button = (JButton) e.getSource();
x = button.getBounds().x;
y = button.getBounds().y;
if (e.getKeyCode() == KeyEvent.VK_UP) {
y = y - 2;
if (y <= 0) {
y = 0;
}
button.setLocation(x, y);
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y = y + 2;
if(y>=300)
y=0;
button.setLocation(x,y);
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
x = x-2;
if (x <= 0) {
x = 300;
}
button.setLocation(x,y);
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x = x+2;
if (x >=300) {
x = 0;
}
button.setLocation(x,y);
}
}
public void keyTyped(KeyEvent e) {

}
public void keyRealsed(KeyEvent e) {

}
public static void main(String[] args) {
new F8();
}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}
}

原文地址:https://www.cnblogs.com/nanfengnan/p/13684045.html