[java] How to Retrieve value from JTextField in Java Swing?

How do we retrieve value from a textfield and actionPerformed()? I need the value to be converted into String for further processing. I have created a textfield on clicking a button I need to store the value entered into a String can you please provide a code snippet?

This question is related to java swing

The answer is


How do we retrieve a value from a text field?

mytestField.getText();

ActionListner example:

mytextField.addActionListener(this);

public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();
}

What I found helpful is this condition that is below.

String tempEmail = "";
JTextField tf1 = new JTextField();

tf1.addKeyListener(new KeyAdapter(){
    public void keyTyped(KeyEvent evt){
         tempEmail = ((JTextField)evt.getSource()).getText() + String.valueOf(evt.getKeyChar());
    }
});

* First we declare JTextField like this

 JTextField  testField = new JTextField(10);

* We can get textfield value in String like this on any button click event.

button.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent ae){
      String getValue = testField.getText()

   }
})

Just use event.getSource() frim within actionPerformed

Cast it to the component

for Ex, if you need combobox

JComboBox comboBox = (JComboBox) event.getSource();
JTextField txtField = (JTextField) event.getSource();

use appropriate api to get the value,

for Ex.

Object selected = comboBox.getSelectedItem();  etc.

testField.getText()

See the java doc for JTextField

Sample code can be:

button.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent ae){
      String textFieldValue = testField.getText();
      // .... do some operation on value ...
   }
})

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Swingtest extends JFrame implements ActionListener
{
    JTextField txtdata;
    JButton calbtn = new JButton("Calculate");

    public Swingtest()
    {
        JPanel myPanel = new JPanel();
        add(myPanel);
        myPanel.setLayout(new GridLayout(3, 2));
        myPanel.add(calbtn);
        calbtn.addActionListener(this);
        txtdata = new JTextField();
        myPanel.add(txtdata);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == calbtn) {
            String data = txtdata.getText(); //perform your operation
            System.out.println(data);
        }
    }

    public static void main(String args[])
    {
        Swingtest g = new Swingtest();
        g.setLocation(10, 10);
        g.setSize(300, 300);
        g.setVisible(true);
    }
}

now its working


You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass