Karvas
Karvas

Reputation: 39

How can i pass jTextField value from one class to another when clicking a jButton?

Greetings from jamaica,

I'm having trouble with a netbeans java project. I have two separate classes: A gui class called MainJFrame.java and another class called main.java.

In the MainJFrame form i have a jTextField and a jbutton. How can i pass the jtextfield value to the main.java class by clicking the jbutton?

thanks.

Upvotes: 1

Views: 1431

Answers (2)

j0chn
j0chn

Reputation: 1113

one possible solution would be to create a third class which handles the communication.
There you would have to register the main.java and pass it to MainJFrame.java.

For Example

public class handler {
    public static main myClass = new main;

    public static main getClass() {
        retunr myClass;
    }

}

Your JFrameMain should containt a new variable

private main mainClass = handler.getClass();

Your onClicklistener should now voi dthe method from your mainClass which gets the text.

mainClass.setText(textFromJText);

Hope i could help you.

Upvotes: 1

Cyrille Ka
Cyrille Ka

Reputation: 15538

  1. You keep a reference to an instance of your Main class in the MainJFrame class.
  2. You define an ActionListener for your JButton.
  3. In this ActionListener, you get the value of the JTextField with JTextField.getText()
  4. And you call a method of Main class on the instance you kept in first step with the text as a parameter.

Upvotes: 1

Related Questions