2013-05-08 125 views
0

我想知道在關注JpopupMenu時是否有任何方法檢測鍵盤輸入。這是爲了消除從鍵盤輸入檢測時對JPopupMenu的關注。這可能嗎?焦點在JpopupMenu上檢測鍵盤輸入(Java)

謝謝。

下面是我寫的簡化代碼。

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import java.net.*; import java.io.*; public class testClass { static JPopupMenu textPopupMenu = new JPopupMenu("MENU"); final static JTextArea textInput = new JTextArea(50,80); final static JPanel overallPanel = new JPanel(); final static JFrame overallFrame = new JFrame("Test"); public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final ActionListener actionListener1 = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { textPopupMenu.setFocusable(false); } }; KeyListener textInputListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { //Get the suggested words from the function and populate them to the JMenuItem textPopupMenu = new JPopupMenu("MENU"); for(int i=0;i<5;i++) { switch(i) { case 0: JMenuItem item1 = new JMenuItem("A"); textPopupMenu.add(item1); break; case 1: JMenuItem item2 = new JMenuItem("B"); textPopupMenu.add(item2); break; case 2: JMenuItem item3 = new JMenuItem("C"); textPopupMenu.add(item3); break; case 3: JMenuItem item4 = new JMenuItem("D"); textPopupMenu.add(item4); break; case 4: JMenuItem item5 = new JMenuItem("E"); textPopupMenu.add(item5); break; }; } textPopupMenu.setFocusable(true); if (textPopupMenu.isVisible()) { textPopupMenu.setLocation(0, 0 + 20); } else { textPopupMenu.show(textInput,0, 0 + 20); } } }; textInput.addKeyListener(textInputListener); overallPanel.add(textInput); overallFrame.getContentPane().add(overallPanel); overallFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);`enter code here` overallFrame.setSize(1000, 900); overallFrame.setLocationRelativeTo(null); overallFrame.setVisible(true); } }); } }
+0

將相同的按鍵偵聽器添加到'JPopupMenu'中? – christopher 2013-05-08 15:09:13

+0

嗨克里斯,我試過使用這個textPopupMenu.addKeyListener(textInputListener);但不幸的是,它不會在焦點時收聽來自鍵盤的任何輸入。 – 2013-05-08 15:11:01

+0

有些代碼可能會幫助我們解決這個問題。 – christopher 2013-05-08 15:31:00

回答

0

是它可以做到這一點使用registerKeyboardAction

KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false); 
    jpopMenu.registerKeyboardAction(actionListener, keystroke, JComponent.WHEN_FOCUSED); 

JComponent.WHEN_FOCUSED將允許你輸入檢測從鍵盤而JPopMenu集中。

+0

嗨Alpesh,謝謝你的回答。我嘗試了你的方法,但它沒有奏效。它仍然專注於JPopupMenu。我在後臺有一個textarea,並且我無法在textarea中寫入任何內容,而JpopupMenu仍處於焦點狀態。 – 2013-05-08 15:22:42

+0

@StephenFebrian,讓你的jpopmenu模態爲false。 – 2013-05-08 15:28:18

+0

@StephenFebrian你能不能粘貼你的代碼,以便我能弄清楚你的代碼是什麼問題? – 2013-05-08 15:31:56

1

我不太確定他們爲什麼這麼做,但必須使用JPopupMenu.addMenuKeyListener()

當我測試了這個,事件被傳遞了兩次,所以我必須存儲從event.getWhen()獲得的最後一個事件的時間,並且只處理比上次存儲時間更新的事件。

相關問題