views:

570

answers:

4

So i creating a little java app and am just wondering how i can get the contents of a JTextField and then assign the value into a String variable, I thought below would work:

JTextField txt_cust_Name = new JTextField();
String cust_Name;
txt_cust_Name.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) 
    {
         cust_Name = txt_cust_Name.getText();
    }
});

Now i thought that this would send the value of the JtextField into the String Cust_Name.

Anyone have any ideas to do this?

Cheers.

+3  A: 

An ActionListener is only fired when the Enter key is pressed.

Maybe you should use a FocusListener and handle the focusLost() event.

Or you can also add a DocumentListener to the Document of the text field. A DocumentEvent is fired every time a change is made to the text field.

camickr
A: 

Normally a JTextField sits on a form and the user gets to play with it until he hits the Ok button on the form. The handler for that button (an ActionListener) then grabs the current text value from the field and does something with it.

Do you want to do something wildly different? Do you need to respond to input as it changes, or only when the user leaves the field? Or is it important that he hit ENTER?

Note that such non-standard behavior would likely confuse a user in real life. If you're just doing this for yourself, of course, anything goes.

Carl Smotricz
A: 

Where ever you need to actually use your string variable, you can just say:

String cust_Name = txt_cust_Name.getText();

This is assuming that at the point in time you are trying to access this value it has already been entered... (As opposed trying to update the variable each time a key is pressed)

instanceofTom
A: 

Thanks all, What i chose to do is to assign the values when a button is pressed:

JButton btn_cust_Save = new JButton("Save Customer");
           btn_cust_Save.addActionListener(new ActionListener()
           {
             public void actionPerformed(ActionEvent ae)
             {
              final String cust_Name = txt_cust_Name.getText();
              final String cust_Door = txt_cust_Door.getText();
              final String cust_Street1 = txt_cust_Street1.getText();
              final String cust_Street2 = txt_cust_Street2.getText();
              final String cust_City = txt_cust_City.getText();
              final String cust_PCode = txt_cust_PCode.getText();
              final String cust_Phone = txt_cust_Phone.getText();
              final String cust_Email = txt_cust_Email.getText();
          }
      });

Thanks for all the help.

TheQuizitor