当我在一个 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;
}
}