做一个矩形上下移动按键在jframe

问题描述:

嗨即时尝试使矩形上下移动的关键按jframe。 但矩形只有当我按向上或向下箭头键,并不停止。我不知道我犯了什么错误。做一个矩形上下移动按键在jframe

我不认为错误是在文件之一,但据说,我无法找到它,所以它可能是。

文件1

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.awt.geom.*; 

public class test{ 

    public static void main (String[] arg) { 
    JFrame window = new JFrame(); 
     test2 t2 = new test2(); 
     window.add(t2); 
     window.setSize(1000,1000); 
     window.setTitle("TEST"); 
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     window.setVisible(true); 
    } 
} 

文件2

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.awt.geom.*; 

public class test2 extends JPanel implements ActionListener, KeyListener{ 

    Timer t = new Timer(5, this); 
    double x = 0, y = 0, velx = 0, vely = 0; 

    public test2() { 
     t.start(); 
     addKeyListener(this); 
     setFocusable(true); 
     setFocusTraversalKeysEnabled(false); 
    } 



    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g; 
     g2.fill(new Rectangle((int)x, (int)y, 20, 40)); 
    } 

    public void actionPerformed(ActionEvent e) { 
     repaint(); 
     x += velx; 
     y += vely; 
    } 

    public void up() { 
     vely = -1.5; 
     velx = 0; 
    } 

    public void down() { 
     vely = 1.5; 
     velx = 0; 
    } 

    public void keyPressed(KeyEvent e) { 
     int code = e.getKeyCode(); 

     if (code == KeyEvent.VK_UP); { 
      up(); 
     } 

     if (code == KeyEvent.VK_DOWN); { 
      down(); 
     } 
    } 

    public void keyTyped(KeyEvent e){} 
    public void keyReleased(KeyEvent e){} 
} 

你的逻辑不是很理想。你应该把你的代码更是这样的:

/** DELETE THIS METHOD! 
public void actionPerformed(ActionEvent e) { 
    repaint(); 
    x += velx; 
    y += vely; 
}**/ 

private static final double MOVEMENT = 1.5; 

public void up() { 
    x += -MOVEMENT; // Mind the - in front of MOVEMENT to negate the value. 
    // No need to change y if it does not change at all 

    repaint() // Repaint _after_ you changed the coordinates 
} 

public void down() { 
    x += MOVEMENT; // Mind that there is no - infront of this MOVEMENT. 
    // No need to change y if it does not change at all 

    repaint() // Repaint _after_ you changed the coordinates 
} 

public void keyPressed(KeyEvent e) { 
    int code = e.getKeyCode(); 

    if (code == KeyEvent.VK_UP); { 
     up(); 
    } 

    if (code == KeyEvent.VK_DOWN); { 
     down(); 
    } 
} 
+0

正如旁注:关于“夹紧”X和Y以避免超出可见区域的值。 – Korashen

你错过呼吁改变x的位置后重绘()onYour的JPanel,Y;

另请注意,您的事件只会触发两次(OnKeyDown和OnKeyUp)。