You are here:

Java/Java TextField in a method


hello and thank you very much for your previous helps!!!!
and now i have another problem!

i have created a textfield using a method:

  public JTextField numberTextField()
     JTextField numberTextField = new JTextField();
     numberTextField.setPreferredSize(new Dimension(150,30));
     return numberTextField;

now i have a Jbutton and would like to get the text from above text field:

  private JButton saveButton()
     JButton saveButton = new JButton("SAVE");
     saveButton.setPreferredSize(new Dimension(250,30));
     saveButton.addActionListener(new ActionListener()

        public void actionPerformed(ActionEvent event)
         AddForm addform = new AddForm();
         String number = addform.numberTextField().getText();
         System.out.println("The value is: " + number);
         //JOptionPane.showMessageDialog(null,"the number is: " + number);
     return saveButton;

now the problem is that this button is not able to get the text!
although if i created the textfield this way:

JTextField numberTextField = new JTextField(25);
then the button can get the text! i do not want to use this approach!

any sugestions!

In your actionPerformed method you create an addForm, that means that anything inside this is separate from other addForms, and the textField isn't set to anything.

All you need to do is make numerTextField a field in your class instead of a variable inside your method. E.g.

public class AddForm extends JPanel {
  private JTextField numberTextField;
  private JButton saveButton;
  public AddForm() {
     numberTextField = new JTextField();
     numberTextField.setPreferredSize(new Dimension(150,30));
     //And so on for the saveButton


All Answers

Answers by Expert:

Ask Experts


Artemus Harper


I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.


I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Washington State University

MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2017 All rights reserved.