0

I've created a JPanel using the NetBeans designer filled with JTextFields and a submit button. I would like to get the values from those JTextFields and use them in my main class. How can I do that?

Also, what are some good tutorials that can help me further understand this? Thank you.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Brian
  • 2,494
  • 1
  • 16
  • 21

2 Answers2

3

I'm guessing you mean JTextField and not TextField. Use the getText() method.

    String text = yourTextField.getText();

Also works with the TextField class, actually.

You'll need an ActionListener on your submit button if you want to grab the text fields' values when a user clicks the button.

    public void actionPerformed(ActionEvent e) {
           if (e.getSource() == yourButtonsName) {
               text = yourTextField.getText();
           }
    }

Don't forget to add the ActionListener!

yourButtonsName.addActionerListener(this);

Or you could use Java 8 lambda expression:

yourButtonsName.addActionerListener(e -> text = yourTextField.getText);

If you'd like to learn more about Java's graphical capabilities, I recommend the Oracle docs: http://docs.oracle.com/javase/tutorial/uiswing/.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
TMBT
  • 1,183
  • 10
  • 17
0

"I've created a JPanel using the NetBeans designer filled with JTextFields and a submit button. I would like to get the values from those JTextFields and use them in my main class. How can I do that?"

Sounds like to me you're facing the class problem of how do I reference instance variables from one, in another.

An easy way would be to pass one class as reference to another and use proper getters and setters. You can see a solution here.

A better solution though would be to create an interface that one of the classes implements and pass that class as an interface to the second class. You can see an example here.

If you feel you're ready for more advanced topics, you should look into MCV Design patterns for this type of problem. MVC is designed for multi-component interaction.

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720