我想尝试在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){}
}
答案 0 :(得分:0)
你的逻辑不是很理想。您的代码应该更像这样:
/** 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();
}
}
答案 1 :(得分:0)
在改变x,y;
的位置后,你错过了在你的JPanel上调用repaint()另请注意,您的事件只会触发两次(OnKeyDown和OnKeyUp)。