出于某种原因,我的程序无法检测到我何时按下某个键,尽管它应该没问题。
这是我的代码:
import javax.swing.*;
public class Frame {
public static void main(String args[]) {
Second s = new Second();
JFrame f = new JFrame();
f.add(s);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Bouncing Ball");
f.setSize(600, 400);
}
}
这是第二堂课:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
public class Second extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
double x = 0, y = 0, velX =0 , velY = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D circle = new Rectangle2D.Double(x, y, 40, 40);
g2.fill(circle);
t.start();
}
public void actionPerformed(ActionEvent e) {
x += velX;
y += velY;
repaint();
}
public void up() {
velY = -1.5;
velX = 0;
}
public void down() {
velY = 1.5;
velX = 0;
}
public void keyPressed(KeyEvent e) {
int KeyCode = e.getKeyCode();
if (KeyCode == KeyEvent.VK_Z) {
up();
}
if (KeyCode == KeyEvent.VK_S) {
down();
}
}
public void keyTyped(KeyEvent e){
}
public void keyReleased(KeyEvent e){
}
}
如何解决这个问题?
最佳答案
计时器似乎不起作用的原因是,
velX
和velY
等于 0,因此,它不会增加任何值。如果你给它们一个值,它就会动画。key 不起作用的原因是
- 因为您尚未将
KeyListener
注册到面板。 - 您需要
setfocusable(true)
。 - 您需要在
up()
down()
方法或中调用repaint()
在keyPressed()
方法中。 - 您需要在
up()
和down()
方法中递增/递减y
值。
- 因为您尚未将
添加以下构造函数,将 repaint()
添加到 keyPressed()
并正确递增/递减,并且可以正常工作
public Second(){
setFocusable(true);
addKeyListener(this);
}
添加上面的构造函数。并在 keyPressed 中重绘
public void keyPressed(KeyEvent e) {
int KeyCode = e.getKeyCode();
if (KeyCode == KeyEvent.VK_Z) {
up();
repaint();
}
if (KeyCode == KeyEvent.VK_S) {
down();
repaint();
}
}
增加/减少
public void up() {
y -= 10;
}
public void down() {
y += 10;
}
<小时/>
虽然这可能有效,但建议使用键绑定(bind)。
查看 How to use Key Bindings | The complete Creating a GUI with Swing trail
关于java - 按键不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20860777/