当我在一个Java应用程序中按“Enter”键时,我正在尝试制作一个示例代码来提交一个文本字段。
我正在使用JFrame和以下代码:
package com.sh.st;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SearchScreen extends JFrame{
JButton btsearch;
JLabel lbsearch;
JTextField txtsearch;
JPanel p1;
public SearchScreen(){
//Button Creation
btsearch= new JButton("Search");
//Label Creation
lbsearch= new JLabel("Type Keywords in english to be searched below:");
//TextBox
txtsearch= new JTextField();
//Pane Creation
p1=new JPanel();
p1.setBackground(Color.gray);
//Pane Components
p1.add(lbsearch);
p1.add(txtsearch);
p1.add(btsearch);
btsearch.setEnabled(true);
//Adding JPaneel
getContentPane().add(p1);
//JFrame Setup
setSize(300,300);
setTitle("SHST");
//JFrame Layout Setup
p1.setLayout(new GridLayout(3,3));
btsearch.setMnemonic(KeyEvent.VK_ENTER);
}
}
但问题是,作为一个虚拟键我需要同时保持“alt”,这太难以理解并且不像用户那样直观。
我试着在堆栈和谷歌这里查看很多页面,但没有一个给我答案。我看到了一些命令,比如“addKeyListener”,但直到现在我才想做我想做的事。
感谢您的帮助
修改[解决方案] :
package com.sh.st;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
public class EventSearch extends SearchScreen{
String query;
public EventSearch(){
txtsearch.getInputMap().put(keyStroke, key);
txtsearch.getActionMap().put(key, enterAction);
}
Action enterAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
try {
HttpRequest http = new HttpRequest(CatchQuery());
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "HTTP request failure.");
}
}};
String key = "ENTER";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
public String CatchQuery(){
query=txtsearch.getText();
this.dispose();
return query;
}
}
答案 0 :(得分:2)
您可以使用KeyBindings
How to use KeyBindings
这是一段代码
final JTextField textfield = new JTextField();
Action enterAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
//do something
}};
String key = "ENTER";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
textfield.getInputMap().put(keyStroke, key);
textfield.getActionMap().put(key, enterAction);
答案 1 :(得分:0)
只需在文本字段中添加一个ActionListener:
//TextBox
txtsearch = new JTextField();
txtsearch.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// code when enter is pressed in text field
}
});