darkagandal
darkagandal

Reputation: 23

Taking a variable from a ComboBox's content

I have a problem with the program that I want to create. I'm a beginner at programming so could you please help me?

Well, I want to take the content of a ComboBox which is inside a void method and use it in an other Class.

Thats the ComboBox: ** ** **

JComboBox ActionComboBox = new JComboBox();
ActionComboBox.addItem("Text");
ActionComboBox.addItem("text2");
ActionComboBox.addItem("text3");
ActionComboBox.setToolTipText("");
ActionComboBox.setBounds(253, 96, 103, 20);
frame.getContentPane().add(ActionComboBox);

** ** **

I want to use the content of that ComboBox from a void method, at a method in another class I use that code to do that:

(I also Import (the name of the class))

** **

private String Action()
{
        String actionBox = ActionComboBox.getSelectedItem();
        return actionBox;
}

** **

Well, the program says that:: ActionComboBox cannot be resolved! as an error.

What should I do?

Thank you

Upvotes: 1

Views: 40

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56499

To accomplish your task, you'll need to follow the steps below.

First, make the line of code below global to the containing class:

JComboBox ActionComboBox = new JComboBox();

Second, create a getter method for the ActionComboBox:

public JComboBox getActionComboBox(){
       return ActionComboBox;
}

then in your other class you can use the getter method to access a reference to the ActionComboBox.

Example, this:

String actionBox = ActionComboBox.getSelectedItem();

would become this:

String actionBox = someInstanceName.getActionComboBox().getSelectedItem().toString();

Upvotes: 1

Related Questions