Slajoc
Slajoc

Reputation: 59

Java | JFrame -> JCombobox : Getting Object(value) by using getSelectedItem?

I'm new to this and I need your help:

I've made a JCombobox with some content. For the content I've used a method including name and value. By referring to the Object(name) I've achieved to display the correct name. Now i want to use JCombobox.getSelectedItem().Object(name) or something like that to get the value of the specific item - but it doesn't work.

Once again, I'm new to this and grateful for any kind of advice ;)

Heres the code:

JComboBox cb_cartype = new JComboBox();
cb_cartype.setBounds(229, 21, 184, 22);
panel.add(cb_cartype);
cb_cartype.setFont(new Font("Arial", Font.BOLD, 14));
cb_cartype.setModel(new DefaultComboBoxModel(new String[] {InsertMethodHere(name)}));


public String InsertMethodHere(String name) {
    name = "Normales Taxi";
    double value = 0.5;
    return name;
}

and later on i want something like this:

double safe = cb_cartype.getSelectedItem().InsertMethodHere(name)

or anything similiar to this

Upvotes: 0

Views: 111

Answers (2)

Ayyoub
Ayyoub

Reputation: 5471

i have no solution for you but if i were you, i will definitely switch to JAVAFX Why ? Swing is out of date, last summer i made an entire project with it and believe the result was awful the GUI keeps freezing, ugly looking and list goes on, sorry for wasting your time to read this even if it wont help you solving your current problem, but its just an advice to you :)

Upvotes: -1

camickr
camickr

Reputation: 324098

Check out Combobox With Custom Renderer for information about this process.

Basically you need to:

  1. Create a custom Object to store the name and value data. You can add this object to the combo box model.
  2. Create a custom renderer to display only the name in the combo box
  3. Create your ActionListener to access the data from the custom object.

You can do each step individually or use the class provided to help simplify the process.

Upvotes: 2

Related Questions