Reputation: 495
Like this i can output the selected value from the ComboBox..
public static String selectedString(ItemSelectable is) {
Object selected[] = is.getSelectedObjects();
return ((selected.length == 0) ? "null" : (String)selected[0]);
}
public static void main(String[] args) {
// Add ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
ItemSelectable is = (ItemSelectable)actionEvent.getSource();
String name=selectedString(is);
System.out.println(name);
}
};
// Add Actionlistener to ComboBox kundeAuswahl
kundeAuswahl.addActionListener(actionListener);
// i wanna have the value of name for use here:
// String test[] = getChildAsArray("kunde","projekt",name);
}
But i would like to get the Value name out of this function, normally i use return, but this gives me an error. How do i have to do this, then?
Upvotes: 1
Views: 2702
Reputation: 13177
You should understand that selecting something in a ComboBox
is an event: the event handler is executed when the event occurs. However, the last lines of your example are executed when the combobox is created.
Therefore, the name
is not available at that time. However, you can call any function you like from the event handler:
public static void main(String[] args) {
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
ItemSelectable is = (ItemSelectable)actionEvent.getSource();
String name=selectedString(is);
doSomethingWithName(name);
}
};
// Add Actionlistener to ComboBox kundeAuswahl
kundeAuswahl.addActionListener(actionListener);
}
public static void doSomethingWithName(String name) {
String test[] = getChildAsArray("kunde","projekt",name);
// ...
}
Upvotes: 1
Reputation: 159
Use a class variable.
class Abc{
String itemname
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
ItemSelectable is = (ItemSelectable)actionEvent.getSource();
String name=selectedString(is);
itemname=name;
System.out.println(name);
}
}
// use itemname in class
}
Upvotes: 1
Reputation: 1116
I'm not exactly sure of what you are trying to achieve but seems like both a class member variable and/or calling a class method from your anonymous class would do the trick.
Also you cannot return a String on public void actionPerformed(ActionEvent actionEvent)
since the method's return type is void.
Upvotes: 0