我正在尝试构建一个NetBeans模块,该模块将由一个选项面板组成,用户必须在该面板中输入他们的凭据和首选项,以及一些在NetBeans编辑器主窗格中跟踪源代码的代码。
目标是通过用户的成功登录激活插件,然后插件将简单地侦听预定义的事件,触发其在编辑器中捕获代码。我不希望用户必须单击菜单栏中的某个项目或某个按钮才能触发代码捕获。它一定不引人注目。
我有几种选择。我想让插件收集Ctrl+S操作或用户按下Enter键、Up键、Down键、Right键、Left键和/或其他键的源代码。
但是,如何将这些类型的事件侦听器添加到TopComponent或活动的NetBeans编辑器中,以便跟踪NetBeans中的用户活动?如何检测用户何时按下编辑器中的某些键?
我终于解决了我的问题。
我使用以下代码片段获得了NetBeans编辑器的活动JTextComponent,然后向其中添加了KeyEventListeners,它运行得很好。
JTextComponent jtc = EditorRegistry.lastFocusedComponent();
jtc.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
int keycode = e.getKeyCode();
switch (keycode) {
case KeyEvent.VK_LEFT:
JOptionPane.showMessageDialog(null, "1 Left: " + e.getKeyCode());
break;
case KeyEvent.VK_RIGHT:
JOptionPane.showMessageDialog(null, "1 Right: " + e.getKeyCode());
break;
case KeyEvent.VK_DOWN:
JOptionPane.showMessageDialog(null, "1 Down: " + e.getKeyCode());
break;
case KeyEvent.VK_UP:
JOptionPane.showMessageDialog(null, "1 Up: " + e.getKeyCode());
break;
case KeyEvent.VK_ENTER:
JOptionPane.showMessageDialog(null, "Enter: "+e.getKeyCode());
break;
}
}
@Override
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
switch (keycode) {
case KeyEvent.VK_LEFT:
JOptionPane.showMessageDialog(null, "2 Left: " + e.getKeyCode());
break;
case KeyEvent.VK_RIGHT:
JOptionPane.showMessageDialog(null, "2 Right: " + e.getKeyCode());
break;
case KeyEvent.VK_DOWN:
JOptionPane.showMessageDialog(null, "2 Down: " + e.getKeyCode());
break;
case KeyEvent.VK_UP:
JOptionPane.showMessageDialog(null, "2 Up: " + e.getKeyCode());
break;
case KeyEvent.VK_ENTER:
JOptionPane.showMessageDialog(null, "Enter: "+e.getKeyCode());
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
int keycode = e.getKeyCode();
switch (keycode) {
case KeyEvent.VK_LEFT:
JOptionPane.showMessageDialog(null, "3 Left: " + e.getKeyCode());
break;
case KeyEvent.VK_RIGHT:
JOptionPane.showMessageDialog(null, "3 Right: " + e.getKeyCode());
break;
case KeyEvent.VK_DOWN:
JOptionPane.showMessageDialog(null, "3 Down: " + e.getKeyCode());
break;
case KeyEvent.VK_UP:
JOptionPane.showMessageDialog(null, "3 Up: " + e.getKeyCode());
break;
case KeyEvent.VK_ENTER:
JOptionPane.showMessageDialog(null, "Enter: "+e.getKeyCode());
break;
}
}
});
因此,这个插件现在允许我使用关键事件捕获用户与活动NetBeans代码编辑器的交互。