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?

+2


source to share


4 answers


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.

+4


source


A simple data class (ideally interface-oriented to minimize congestion) should do the trick. Or, if item names and such can change at runtime, it might be fine java.util.Map

.



+1


source


You can use Java Observer and pass any object as an argument on state change.

+1


source


Use parameters.

otherObject.doStuff(comboBoxValue, slider1Value, slider2Value);

      

The method you are calling must be declared to accept the number of parameters you want to pass:

class OtherObject {
    ...
    void doStuff(int value1, int value2, int value3);
}

      

0


source







All Articles