Hallo,
Kann ich bei einer JAVA-Combo-Box bei addItem nicht nur einen String, sondern auch noch einen Value hinzufügen
Du kannst einer JComboBox mit .addItem(Object anObject) überhaupt _nur_ Objekte hinzufügen. Natürlich können das auch spezielle, von Dir erstellte, Objekte sein.
Beispiel:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyJComboBox extends JFrame implements ActionListener{
public MyJComboBox() {
super("JList Sampler Demo");
initList();
}
public void initList() {
JComboBox jcbb = new JComboBox();
jcbb.addItem(new TextValuePair("text1", "value1"));
jcbb.addItem(new TextValuePair("text2", "value2"));
jcbb.addItem(new TextValuePair("text3", "value3"));
jcbb.addActionListener(this);
Container cp = this.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jcbb);
}
public void actionPerformed(ActionEvent e) {
JComboBox jcbb = (JComboBox)e.getSource();
String text = ((TextValuePair)jcbb.getSelectedItem()).text;
String value = ((TextValuePair)jcbb.getSelectedItem()).value;
System.out.println(text + " " + value);
}
private final class TextValuePair {
final String text;
final String value;
TextValuePair(String text, String value) {
this.text = text;
this.value = value;
}
public String toString() {
return this.text;
}
}
public static void main(String[] args) {
JFrame frame = new MyJComboBox();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.pack();
frame.setSize(200,100);
frame.setVisible(true);
}
}
viele Grüße
Axel