要接收键盘事件,您必须使用
以下两个处理程序都不是在按键时执行的:
public class Try_KeyboardInput_01 {
private static final Logger log = LoggerFactory.getLogger(Try_KeyboardInput_01.class);
@SuppressWarnings("serial")
public static void main(String[] args) {
new PFrame() {
@Override
public void initialize() {
PPath circle = PPath.createEllipse(-100, -100, 200, 200);
getCanvas().getLayer().addChild(circle);
circle.addInputEventListener(new PBasicInputEventHandler() {
@Override
public void keyPressed(PInputEvent event) {
log.info("Key pressed on circle");
}
});
getCanvas().getLayer().addInputEventListener(new PBasicInputEventHandler() {
@Override
public void keyPressed(PInputEvent event) {
log.info("Key pressed on layer");
}
});
getCanvas().addInputEventListener(new PBasicInputEventHandler() {
@Override
public void keyPressed(PInputEvent event) {
log.info("Key pressed on canvas");
}
});
}
};
}
}
如何激活该功能?
更新
在我看到的一些演示中,可以从鼠标处理程序中打开键盘焦点。但若电脑并没有鼠标,或者默认情况下应该打开键盘操作,那个么这是不可接受的。
如何显式打开键盘处理?
更新2
仍然不明白,是否可以将键盘焦点设置在特定节点上(无需鼠标)。
PInputManager.setKeyboardFocus
设置一个处理程序。例如:
getCanvas().getRoot().getDefaultInputManager().setKeyboardFocus(new PBasicInputEventHandler() {
@Override
public void keyPressed(PInputEvent event) {
switch (event.getKeyCode()) {
//TODO
}
}
});
或基于节点:
PBasicInputEventHandler handler = new PBasicInputEventHandler() {
@Override
public void mousePressed(final PInputEvent event) {
event.getInputManager().setKeyboardFocus(event.getPath());
event.setHandled(true);
}
@Override
public void keyPressed(PInputEvent event) {
System.out.println(event.getPickedNode());
}
};
根据实际情况,有许多变化。有关开发人员打算如何处理键盘事件的一些示例,请参阅PSelectionEventHandler
和KeyEventFocusExample
源代码。
编辑:
import java.awt.event.KeyEvent;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolox.PFrame;
public class DemoKeyboard {
static class SampleHandler extends PBasicInputEventHandler {
private PNode activeNode;
public void setActiveNode(PNode activeNode) {this.activeNode = activeNode;}
public PNode getActiveNode() {return activeNode;}
@Override
public void keyPressed(PInputEvent event) {
if (activeNode == null)
return;
switch (event.getKeyCode()) {
case KeyEvent.VK_LEFT: activeNode.translate(-5, 0); break;
case KeyEvent.VK_UP: activeNode.translate(0, -5); break;
case KeyEvent.VK_RIGHT: activeNode.translate(5, 0); break;
case KeyEvent.VK_DOWN: activeNode.translate(0, 5); break;
}
}
};
public static void main(String[] args) {
new PFrame() {
@Override
public void initialize() {
final PPath circle = PPath.createEllipse(0, 0, 200, 200);
getCanvas().getLayer().addChild(circle);
SampleHandler handler = new SampleHandler();
handler.setActiveNode(circle);
getCanvas().getRoot().getDefaultInputManager().setKeyboardFocus(handler);
}
};
}
}