I'm trying to learn Jtextfields and action listeners. I was following this tutorial https://www.geeksforgeeks.org/java-swing-jtextfield/, but I'm encountering an error with this function.
public void actionPerformed(ActionEvent e) {
String input = e.getActionCommand();
if (input.equals("submit")) {
displaysText.setText(textField.getText());
textField.setText("");
System.out.println("Entered if statement");
}
}
No matter what I input into the text field it will enter that if statement. It should just enter that if statement when I enter "submit". Is this a bug or am I doing something wrong?
If it's any help here is all of the code
package IncludesMain;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JFrame implements ActionListener {
static JTextField textField;
static JFrame frame;
static JButton button;
static JLabel displaysText;
Main() {}
public static void main(String[] args) {
frame = new JFrame("textfield");
displaysText = new JLabel("N/A");
button = new JButton("submit");
Main textObject = new Main();
button.addActionListener(textObject);
textField = new JTextField(16);
JPanel panel = new JPanel();
panel.add(textField);
panel.add(button);
panel.add(displaysText);
frame.add(panel);
frame.setSize(500, 400);
frame.show();
}
public void actionPerformed(ActionEvent e) {
String input = e.getActionCommand();
if (input.equals("submit")) {
displaysText.setText(textField.getText());
textField.setText("");
System.out.println("Entered if statement");
}
}
}
The e.getActionCommand()
is taking the actionCommand of the button, because you are putting the listener on there. You need to set the listener on the textfield
Instead of
Main textObject = new Main();
button.addActionListener(textObject);
textField = new JTextField(16);
JPanel panel = new JPanel();
It should be
Example textObject = new Example();
textField = new JTextField(16);
textField.addActionListener(textObject);
JPanel panel = new JPanel();
Also if you do this then you must press Enter to submit the value, the button won't work unless you refactor the logic inside the actionPerformed method