Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Newbie JComboBox Key/Value pairs



>I'm trying to create a drop down menu similar to what you'd get with <HTML>,
>in that you can specify a name/value pair - the name being the value you
>need (in my case an int id number) and a String value for display to the
>user.

A JListBox can contain objects of any type. The thing that will gets dispayed is the toString() representation of the object.

The easiest way to do this is to create an inner class. Here is a fully working example.

Regards,

Frederik
--------------------

import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Main extends JFrame {
JComboBox combo;

public Main() {
Option[] options = new Option[]{new Option(1, "test"), new Option(2, "test2")};
combo = new JComboBox(options);
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("id selected: " + ((Option)combo.getSelectedItem()).id);
}

});
this.getContentPane().add(combo);
this.setSize(200, 64);

}

public static void main(String[] args) {
Main m = new Main();
m.show();
}

public class Option {
public Option(int id, String value) {
this.id = id;
this.value = value;
}

public int id;
public String value;

public String toString() {
return value;
}

}

}
_______________________________________________
java-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/java-dev
Be sure to read the FAQ http://developer.apple.com/java/faq/ before posting
Do not post admin requests to the list. They will be ignored.

References: 
 >Newbie JComboBox Key/Value pairs (From: George Piponidou <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.