解决方案 »

  1.   

    你的方块不在坚挺
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Paint;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.Timer;
    import java.util.TimerTask;import javax.swing.JFrame;
    import javax.swing.JPanel;public class KeyTest extends JFrame { private JFrame jFrame; private JPanel jPanel; private Paint jPanelPanel; private MyPaint panel; private Graphics g;
    static Timer t = new Timer(); private int x1 = 20, y1 = 20; public KeyTest() {
    jFrame = new JFrame("welcome to tianyaleke...");
    panel = new MyPaint(x1, y1); panel.setFocusable(true);
    jFrame.add(panel);
    jFrame.setSize(400, 400); jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
    jFrame.setVisible(true); panel.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    // System.out.println(e.VK_UP);
    if (key == e.VK_UP) {
    x1 = x1 - 5;
    y1 = y1;
    panel.setX1(x1);
    panel.setY1(y1);
    panel.repaint();
    System.out.println("dsdsd"); } else if (key == e.VK_DOWN) {
    x1 = x1 + 5;
    y1 = y1;
    panel.setX1(x1);
    panel.setY1(y1);
    panel.repaint();
    System.out.println("dsdsd");
    } else if (key == e.VK_LEFT) {
    x1 = x1;
    y1 = y1 - 5;
    panel.repaint();
    } else if (key == e.VK_RIGHT) {
    x1 = x1;
    y1 = y1 + 5;
    panel.repaint();
    } }
    }); } public static void main(String[] args) {
    KeyTest kt = new KeyTest();
    kt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}class MyPaint extends JPanel {
    private int x1, y1; public MyPaint(int x1, int y1) {
    this.x1 = x1; this.y1 = y1; } public int getX1() {
    return x1;
    } public void setX1(int x1) {
    this.x1 = x1;
    } public int getY1() {
    return y1;
    } public void setY1(int y1) {
    this.y1 = y1;
    } public void paint(Graphics g) {
    super.paintComponent(g);
    g.fillRect(x1, y1, 40, 40);
    }
    }