tags:

views:

1461

answers:

5

This is probably a really simple problem, but I can't figure out how to do it.

I have a GUI class with a listener which takes variables from comboboxes and sliders. I need it to pass these variables into a method in another class which will run on an object in that class.

How can I do this?

+1  A: 

A simple data class (ideally fronted by an interface, to minimize coupling) should do the trick. Or if the data member names and such vary at runtime, a java.util.Map may be appropriate.

T.J. Crowder
+1  A: 

You can use Java's Observer and pass any object as the argument when the state is changing.

Mickel
+2  A: 

There are two common approaches. The simple one, often used for dialogs, makes the selected values (e.g. your combobox selection) available for other classes, the second one allows other classes to register on your object to receive update notifications.

First approach

  1. store the actual selections of your GUI elements in (private) member variables (like: private String currentSelection). This is done by the listener that you already implemented.
  2. implement a method like String getSelection()
  3. When the dialog is done (like someone pressed the OK button), fetch the value by simply calling the getSelection() method

This can be used if you offer a dialog for a user to enter some values. The file chooser dialogs are a typical example. If you require 'real time' access to the current selection, then use the:

Second approach

  1. Implement the Observer Pattern (Listener class, eventually an event class)

The pattern is a bit too complex to explain it step by step and in detail, but there's a lot of documentation and examples around, if you're interested and really need this realtime access to changes.

Andreas_D
A: 

You can implement Interface.

Satalink
A: 

Use parameters.

otherObject.doStuff(comboBoxValue, slider1Value, slider2Value);

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

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