Java: passing variables across classes
This is probably a very simple problem, but I can't figure out how to do it.
I have a GUI class with a listener that accepts variables from comboboxes and sliders. I need to pass these variables to a method in another class that will work on an object in that class.
How can i do this?
source to share
There are two general approaches. A simple one, often used for dialogs, makes selected values (like your combo box choice) available to other classes, the second allows other classes to register with your object to receive update notifications.
First approach
- store the actual selection of GUI elements in (private) member variables (ex:)
private String currentSelection
. This is done by the listener you have already implemented. - implement a method like
String getSelection()
- When the dialog is complete (for example, someone clicked the OK button), select the value by simply calling the method
getSelection()
This can be used if you are offering a dialog for the user to enter some values. File selection dialogs are typical examples. If you require realtime access to the current selection, use:
Second approach
- Implement observer pattern (listener class, ultimately event class)
The template is too complex to explain step by step and in detail, but there is a lot of documentation and examples around if you are interested and really need this real-time access to changes.
source to share