我正在使用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似乎不是真的!
请帮忙!我究竟做错了什么?
答案 0 :(得分:1)
没有Canvas和EventQueue的代码会有点困难,但通常我会使用一个关键监听器来包含画布:
//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());
}
});