2012-12-12 34 views
-1

我試圖在使用回車鍵時使用jTextField執行搜索。 searchButton執行搜索,因此我需要在文本字段中按下按鍵的操作來觸發searchButton的操作。在GUI中使用回車鍵執行搜索

下面是我剛纔所說的,當我在文本字段中按Enter鍵時,控制檯上顯示「Enter Pressed」。

ActionListener actionListener = new ActionListener() { 
    public void actionPerformed(ActionEvent actionEvent) { 
    SearchButton.getActionForKeyStroke(
     KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)); 
    System.out.println("Enter Pressed"); 
    } 
}; 

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

回答

1

爲什麼不重複使用相同的ActionListener的文本框和按鈕?

或者,如果你沒有訪問到該按鈕的監聽器,你可能只是這樣做:

jTextField1.addActionListener(new ActionListener() 
{ 
    public void actionPerformed(ActionEvent actionEvent) 
    { 
    searchButton.doClick(); 
    } 
} 
+0

或最好定義一個'Action'並將其添加到兩個按鈕和文本字段。 –