You are here:

Java/Java TextField in a method

Advertisement


Question
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!

Answer
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));
     add(numberTextField;
     //And so on for the saveButton
  }
}

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

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

Experience

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#

Organizations
Washington State University

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

©2016 About.com. All rights reserved.