Detect enter press in JTextField
A JTextField
was designed to use an ActionListener
just like a JButton
is. See the addActionListener()
method of JTextField
.
For example:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("some action");
}
};
JTextField textField = new JTextField(10);
textField.addActionListener( action );
Now the event is fired when the Enter key is used.
Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button.
JButton button = new JButton("Do Something");
button.addActionListener( action );
Note, this example uses an Action
, which implements ActionListener
because Action
is a newer API with addition features. For example you could disable the Action
which would disable the event for both the text field and the button.
How to get a JTextField to respond to the enter key
Forget about using KeyListener
for Swing
components.
This listener was designed for use with AWT
components does not provide a reliable interaction mechanism for JTextComponents
.
Use an ActionListener
instead - on the vast majority of systems an ActionEvent
is dispatched by the JTextField
when enter is pressed.
myTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myTextArea.append(myTextField.getText() + "\n");
}
});
detect enter key in JTextField and do something in actionperformed
Firstly, actionPerformed
is triggerd by an action event, typically on most systems, this is triggered by the Enter key (with context to the JTextField
)...so you don't need to check for it.
Secondly, the source
of the ActionEvent
is typically the control that triggered it, that would be the JTextField
in this case.
Thirdly, String
comparison in Java is done via the String#equals
method...
if ("Enter presses".equals(someOtherString)) {...
Enter key JTextField
- have to create an temporary
Object
for comparisons
for example
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == btnEmptyBasket) {
//...........
} else if (source == txtProductAantal) {
//...........
} else {
}
}
- or there are only
JTextFields
(avoidinginstanceof
insideif - else
statement) you can casting Object toJTextField
directly
JTextField source = (JTextField) event.getSource();
EDIT,
one from the next adviced 17 problems.
please to read suggestion by @Andrew Thompson, again
1) For better help sooner, post an SSCCE.
2) txtProductAantal.setBounds(..)
Use layouts to avoid the next 17 problems.
my code works as I'm expected
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class JTextFieldAndActionListener implements ActionListener {
private JFrame frm = new JFrame("JTextFieldAndActionListener");
private JTextField one = new JTextField(10);
private JTextField two = new JTextField();
private JTextField three = new JTextField();
public JTextFieldAndActionListener() {
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
frm.setLayout(new GridLayout());
frm.add(one);
frm.add(two);
frm.add(three);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLocation(400, 300);
frm.pack();
frm.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == one) {
System.out.println("firing from JTextField one");
} else if (source == two) {
System.out.println("firing from JTextField two");
} else if (source == three) {
System.out.println("firing from JTextField three");
} else {
System.out.println("something went wrong");
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JTextFieldAndActionListener ie = new JTextFieldAndActionListener();
}
});
}
}
print_out me on ENTER key
run:
firing from JTextField one
firing from JTextField two
firing from JTextField three
BUILD SUCCESSFUL (total time: 15 seconds)
pressing ENTER key do not work for JTextField in applet
This seems to work for me....
public class TestApplet04 extends JApplet implements ActionListener {
private JTextField textField;
private JTextArea textArea;
private String newline;
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
// question = ProcessString(question);
// answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
}
Updated after feedback
Here's you major problem...
sc = new Scanner(new File("database.txt"));
This is going to cause you a number of problems. First of all, the applet isn't likely to have access rights to read from the client machine, so you're likely to run into a security exception. Secondly, as the previous statement may have suggested, the file ins't likely to exist on the client machine.
You need to embed this resource within the Jar of your application and use getClass().getResource("...")
to gain access to it. This will return a URL
, from which you can use URL#openConnection
to gain access to a InputStream
, which can use in your scanner.
Programmatically trigger a key events in a JTextField?
Do not use
KeyListener
onJTextField
simply addActionListener
which will be triggered when ENTER is pressed (thank you @robin +1 for advice)JTextField textField = new JTextField();
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
//do stuff here when enter pressed
}
});To trigger
KeyEvent
userequestFocusInWindow()
on component and useRobot
class to simulate key press
Like so:
textField.requestFocusInWindow();
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
} catch (AWTException e) {
e.printStackTrace();
}
Example:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Here..");
}
});
frame.add(textField);
frame.pack();
frame.setVisible(true);
textField.requestFocusInWindow();
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
} catch (AWTException e) {
e.printStackTrace();
}
}
});
}
}
UPDATE:
As others like @Robin and @mKorbel have suggested you might want a DocumentListener
/DocumentFiler
(Filter allows validation before JTextField
is updated).
You will need this in the event of data validation IMO.
see this similar question here
it shows how to add a DocumentFilter
to a JTextField
for data validation. The reason for document filter is as I said allows validation before chnage is shown which is more useful IMO
How do I pick up the Enter Key being pressed in JavaFX2?
You can use the onAction attribute of the TextField and bind it to a method in your controller.
@FXML
public void onEnter(ActionEvent ae){
System.out.println("test") ;
}
And in your FXML file:
<TextField fx:id="textfield" layoutX="29.0" layoutY="298.0" onAction="#onEnter" prefWidth="121.0" />
switching JTextFields by pressing Enter key
Simple example:
Suppose you have two JTextField
s: textField
and textField1
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textField1.requestFocusInWindow();
}
});
textField1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textField.requestFocusInWindow();
}
});
Now when you hit Enter
when focused on the first JTextField
, the other one will be focused, and vice versa.
Related Topics
Which Loop Has Better Performance? Why
Java Parsing Xml Document Gives "Content Not Allowed in Prolog." Error
What Does the 'New' Keyword Actually Do in Java, and Should I Avoid Creating New Objects
Java/Jaxb: Unmarshall Xml to Specific Subclass Based on an Attribute
Java Restfull Webservice: Jax-Rs Implementation with Jersey 2.3.1 Libraries
Any Good Recommendations for Mp3/Sound Libraries for Java
Adding and Subtracting Chars, Why Does This Work
Java.Lang.Classnotfoundexception: Org.Springframework.Boot.Springapplication Maven
Print Full Call Stack on Printstacktrace()
Accessing Constructor of an Anonymous Class
Converting Date-String to a Different Format
Rgb to Cmyk and Back Algorithm
Effect of a Bitwise Operator on a Boolean in Java
Java String.Replace/Replaceall Not Working
Javafx and Maven: Nullpointerexception: Location Is Required