java,swing,在 textField中输入完成后,直接按回车键就执行“查询”操作,怎么写代码?
finalJButtonbutton=newJButton("查询");button.addActionListener(newActionListener(){@Ove...
final JButton button = new JButton("查询");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
database = textField.getText().trim();
c1=comboBox.getSelectedIndex();
switch(c1){
case 0: baite_select_reader.chaxunrenyuan();break;
// case 1: baite_select_book.chaxuntushu();break;
}
}
}); ///// 展开
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
database = textField.getText().trim();
c1=comboBox.getSelectedIndex();
switch(c1){
case 0: baite_select_reader.chaxunrenyuan();break;
// case 1: baite_select_book.chaxuntushu();break;
}
}
}); ///// 展开
2015-07-25
展开全部
使用的时候,只要将SwingUtils .enterPressesWhenFocused(JButton)这样就可以实现回车时候,触发按钮。
另外文本输入框回车触发事件则是:SwingUtils .enterPressesWhenFocused(JTextField textField,ActionListener actionListener) 。其中actionListener是需要触发的事件。
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
//SwingUtils 实用方法类
public class SwingUtils {
/**
* 对指定的button添加回车驱动事件的功能
* @param button
*/
public static void enterPressesWhenFocused(JButton button) {
button.registerKeyboardAction(button.getActionForKeyStroke(KeyStroke
.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED);
button.registerKeyboardAction(button.getActionForKeyStroke(KeyStroke
.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED);
}
另外文本输入框回车触发事件则是:SwingUtils .enterPressesWhenFocused(JTextField textField,ActionListener actionListener) 。其中actionListener是需要触发的事件。
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
//SwingUtils 实用方法类
public class SwingUtils {
/**
* 对指定的button添加回车驱动事件的功能
* @param button
*/
public static void enterPressesWhenFocused(JButton button) {
button.registerKeyboardAction(button.getActionForKeyStroke(KeyStroke
.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED);
button.registerKeyboardAction(button.getActionForKeyStroke(KeyStroke
.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询