shakkir3435
shakkir3435

Reputation: 133

Get value from JPanel textfield in another class

I have JPanel with text box, save button in another panel. If I click the save button I have to get the 1st panel text box value.

How to access it?

Upvotes: 3

Views: 14504

Answers (4)

Francisco Puga
Francisco Puga

Reputation: 25158

An easy solution will be create a constructor in the class where you implement your ActionListener and pass in the constructor the components that you need to update or to retrieve values.

This solution will work, but there is a better approach that allows make the code more reusable. Take a look at the observer pattern and use it in your code.

Upvotes: 2

basiljames
basiljames

Reputation: 4847

You should have a Controller class from where you create the panel. Keep reference to the panel in the controller class. Expose a getter method in your CustomPanel1 to return the text in the TextField(not the textfield itself). Similarly you create the second CustomPanel2 also from the Controller and keep reference. Define the listener class in your controller and pass it to your second panel. In the second panel add the listener to your button.

This would be a simple solution.

Swing Tutorial

Upvotes: 0

Azuu
Azuu

Reputation: 856

Just make the TextField as Public Static dats it. And then u can Access the TextField Using ClassName.TextFiledName

Upvotes: 6

nt.bas
nt.bas

Reputation: 756

Well since there's no SSCCE, this will be a general answer.
First you could make the text box public static field and access it from the other class but that will be one of the worst code you will ever write. Second you can use setters/getters methods which are cool but don't behave well as your program grows complex. Setters/getters will create tight coupling between components. Finally I suggest using the Observer pattern. It may seem like using a nuke against a bicycle but in the end it is well worth the initial trouble - and you learn something in the process.
More information and example source code can be found at Source making.

Upvotes: 0

Related Questions