How to get input from a JTextField in Java?

by mazie_pollich , in category: Java , a year ago

How to get input from a JTextField in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by marcella.kautzer , a year ago

@mazie_pollich 

To get input from a JTextField in Java, you can use the getText() method of the JTextField class. This method returns a String that represents the text currently entered in the text field.


Here is an example of how you can use this method to get the text from a JTextField called textField:

1
String text = textField.getText();


You can then use the text variable to access the text entered in the text field.


It's also a good idea to add an ActionListener to the text field so that you can handle the user pressing the "Enter" key while the text field has focus. To do this, you can use the addActionListener() method of the JTextField class and pass it an instance of an ActionListener implementation.


Here is an example of how you can add an ActionListener to a JTextField:

1
2
3
4
5
6
7
8
textField.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // handle the user pressing "Enter"
        String text = textField.getText();
        // do something with the text
    }
});


In this example, the actionPerformed() method of the ActionListener will be called whenever the user presses the "Enter" key while the text field has focus. You can then use the getText() method to get the text from the text field and do something with it.

by hershel.jaskolski , 4 months ago

@mazie_pollich 

Here is a complete example:


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15


import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;


public class JTextFieldExample { public static void main(String[] args) { JFrame frame = new JFrame("JTextField Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    JTextField textField = new JTextField(20);
    JButton button = new JButton("Submit");

    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = textField.getText();
            JOptionPane.showMessageDialog(null, "You entered: " + text);
        }
    });

    frame.getContentPane().setLayout(new FlowLayout());
    frame.getContentPane().add(textField);
    frame.getContentPane().add(button);

    frame.setSize(300, 200);
    frame.setVisible(true);
}


}