JComboBox setting label and value
Is it possible to set a value and a label to a JComboBox
so I can show a label but get a value that is different?
For example in JavaScript I can do:
document.getElementById("myselect").options[0].value //accesses value attribute of 1st option
document.getElementById("myse开发者_如何学Golect").options[0].text //accesses text of 1st option
You can put any object inside of a JComboBox. By default, it uses the toString method of the object to display a label navigate in the combo box using the keyboard. So, the best way is probably to define and use appropriate objects inside the combo :
public class ComboItem {
private String value;
private String label;
public ComboItem(String value, String label) {
this.value = value;
this.label = label;
}
public String getValue() {
return this.value;
}
public String getLabel() {
return this.label;
}
@Override
public String toString() {
return label;
}
}
Here's a utility interface and class that make it easy to get a combo box to use different labels. Instead of creating a replacement ListCellRenderer
(and risking it looking out of place if the look-and-feel is changed), this uses the default ListCellRenderer
(whatever that may be), but swapping in your own strings as label text instead of the ones defined by toString()
in your value objects.
public interface ToString {
public String toString(Object object);
}
public final class ToStringListCellRenderer implements ListCellRenderer {
private final ListCellRenderer originalRenderer;
private final ToString toString;
public ToStringListCellRenderer(final ListCellRenderer originalRenderer,
final ToString toString) {
this.originalRenderer = originalRenderer;
this.toString = toString;
}
public Component getListCellRendererComponent(final JList list,
final Object value, final int index, final boolean isSelected,
final boolean cellHasFocus) {
return originalRenderer.getListCellRendererComponent(list,
toString.toString(value), index, isSelected, cellHasFocus);
}
}
As you can see the ToStringListCellRenderer
gets a custom string from the ToString
implementation, and then passes it to the original ListCellRenderer
instead of passing in the value object itself.
To use this code, do something like the following:
// Create your combo box as normal, passing in the array of values.
final JComboBox combo = new JComboBox(values);
final ToString toString = new ToString() {
public String toString(final Object object) {
final YourValue value = (YourValue) object;
// Of course you'd make your own label text below.
return "custom label text " + value.toString();
}
};
combo.setRenderer(new ToStringListCellRenderer(
combo.getRenderer(), toString)));
As well as using this to make custom labels, if you make a ToString
implementation that creates strings based on the system Locale, you can easily internationalize the combo box without having to change anything in your value objects.
Please, can show me a full example?
Instances of Enum
are particularly convenient for this, as toString()
"returns the name of this enum constant, as contained in the declaration."
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** @see http://stackoverflow.com/questions/5661556 */
public class ColorCombo extends JPanel {
private Hue hue = Hue.values()[0];
public ColorCombo() {
this.setPreferredSize(new Dimension(320, 240));
this.setBackground(hue.getColor());
final JComboBox colorBox = new JComboBox();
for (Hue h : Hue.values()) {
colorBox.addItem(h);
}
colorBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Hue h = (Hue) colorBox.getSelectedItem();
ColorCombo.this.setBackground(h.getColor());
}
});
this.add(colorBox);
}
private enum Hue {
Cyan(Color.cyan), Magenta(Color.magenta), Yellow(Color.yellow),
Red(Color.red), Green(Color.green), Blue(Color.blue);
private final Color color;
private Hue(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
}
private static void display() {
JFrame f = new JFrame("Color");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new ColorCombo());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
display();
}
});
}
}
Use ListCellRenderer to achieve what you want. Make a class that extends JLabel
and implements ListCellRenderer
. Set that class as a renderer in your JComboBox
using setRenderer()
method. Now when you access values from your jcombobox it will be of type jlabel.
Step 1
Create a class with the two properties of the JComboBox
, id, name for example
public class Product {
private int id;
private String name;
public Product(){
}
public Product(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//this method return the value to show in the JComboBox
@Override
public String toString(){
return name;
}
}
Step 2
In the design of the form, right click in the JComboBox
and select Properties, now open the code tab and in the property Type Parameters write the name of the class, in our example it is Product.
Step 3
Now create a method that connects to the database with a query to generate a list of products, this method receives as a parameter a JComboBox
object.
public void showProducts(JComboBox <Product> comboProduct){
ResultSet res = null;
try {
Connection conn = new Connection();
String query = "select id, name from products";
PreparedStatement ps = conn.getConecction().prepareStatement(query);
res = ps.executeQuery();
while (res.next()) {
comboProduct.addItem(new Product(res.getInt("id"), res.getString("name")));
}
res.close();
} catch (SQLException e) {
System.err.println("Error showing the products " + e.getMessage());
}
}
Step 4 You can call the method from the form
public frm_products() {
initComponents();
Product product = new Product();
product.showProducts(this.cbo_product);
}
Now you can access the selected id using getItemAt
method
System.out.println(cbo_product.getItemAt(this.cbo_product.getSelectedIndex()).getId());
精彩评论