由于某些原因,我的程序没有检测到当我按下一个键,即使它应该是好的。
这是我的密码:
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){
}
}我该如何解决这个问题?
发布于 2013-12-31 17:24:48
velX和velY等于0,所以它不会增加任何东西。如果你给他们一个价值,它就会有活力。1. because you haven't registered the `KeyListener` to the panel.
2. you need to `setfocusable(true)`.
3. You need to call `repaint()` in the either the `up()` `down()` methods _or_ in the `keyPressed()` method.
4. You need to increment/decrement the `y` value in the `up()` and `down()` methods.
添加下面的构造函数,将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;
}虽然这可能有效,但建议使用键绑定。
见 如何使用键绑定 \ 使用Swing跟踪创建GUI的完整过程
发布于 2013-12-31 17:19:36
为了进行测试,向JFrame中添加一个侦听器,并查看那里是否有任何响应。如果您这样做了,那么这意味着JFrame没有将事件传递到第二个事件,可能是因为第二个事件没有焦点。
您也可以尝试调用requestFocusInWindow():http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html
当用户单击某个组件时,或者当用户在组件之间选择选项卡,或者以其他方式与组件交互时,组件通常会获得焦点。组件也可以通过编程方式获得焦点,例如当其包含的框架或对话框被显示时。此代码片段显示了如何在窗口每次获得焦点时为特定组件提供焦点:
//Make textField get the focus whenever frame is activated.
> f.addWindowFocusListener(new WindowAdapter() {
> public void windowGainedFocus(WindowEvent e) {
> s.requestFocusInWindow();
> } });我还建议使用比s、f更多的描述性变量,并使用比Second更具有描述性的类名。
https://stackoverflow.com/questions/20860777
复制相似问题