Get value from JPanel textfield in another class

2020-03-04 20:54发布

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?

标签: java swing
4条回答
放我归山
2楼-- · 2020-03-04 21:16

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

查看更多
够拽才男人
3楼-- · 2020-03-04 21:20

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.

查看更多
Evening l夕情丶
4楼-- · 2020-03-04 21:26

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.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-03-04 21:37

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

查看更多
登录 后发表回答