我正在使用JCanvas创建一个简单的Java应用程序,我需要获取用户按下的键的键代码:以下是Java代码的简化版本。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.EventObject;
import java.awt.event.*;
// myJavaFiles project contains JCanvas & JEventQueue Classes
import myJavaFiles.*;
import javax.swing.*;
public static void main(String[] args) {
JCanvas canvas = new JCanvas();
JEventQueue events = new JEventQueue();
events.listenTo(canvas, "canvas");
JFrame frame = new JFrame();
frame.setSize(700, 700);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setFocusable(true);
frame.add(canvas);
while (true) {
if (events.hasEvent()){
EventObject event = events.waitEvent();
if(JEventQueue.isKeyPressed(event)){
int keycode = events.getKeyCode(event);
// USE KEYCODE!!!
}
}
canvas.sleep(10);
canvas.clear();
}
}
一切正常(我省略了很多无关的代码),除了按下键外,我确实注意到events.hasEvent甚至在我按下键时都不是真的!
请帮忙!我究竟做错了什么?
最佳答案
如果没有JCanvas和JEventQueue的代码,这会有些困难,但是通常我会在包含画布的面板上使用键侦听器:
//frame.add(canvas);
final JPanel panel = new JPanel();
panel.add(canvas);
frame.getContentPane().add(panel);
panel.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent keyEvent) {
System.out.println("keyEvent.getKeyCode(): " + keyEvent.getKeyCode());
}
});
关于java - 使用JCanvas时获取KeyPressed,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27043582/