import java.awt.*;
import javax.swing.*;
public class CustomComboBoxDemo extends JPanel {
static class VO {
private int id;
private String description;
public VO(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
private static final VO[] numeros = {new VO(1, "Impar"), new VO(2, "Par"), new VO(3, "Impar"), new VO(4, "Par"), new VO(5, "Impar"), new VO(6, "Par"), new VO(7, "Impar"), new VO(8, "Par")};
public CustomComboBoxDemo() {
super(new BorderLayout());
Integer[] intArray = new Integer[numeros.length];
for (int i = 0; i < numeros.length; i++) {
intArray[i] = new Integer(i);
}
//Create the combo box.
JComboBox petList = new JComboBox(intArray);
ComboBoxRenderer renderer = new ComboBoxRenderer();
//renderer.setPreferredSize(new Dimension(200, 130));
petList.setRenderer(renderer);
petList.setMaximumRowCount(5);
//Lay out the demo.
add(petList, BorderLayout.PAGE_START);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CustomComboBoxVODemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new CustomComboBoxDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
class ComboBoxRenderer extends JLabel
implements ListCellRenderer {
public ComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(RIGHT);
setVerticalAlignment(CENTER);
}
/*
* This method finds the image and text corresponding
* to the selected value and returns the label, set up
* to display the text and image.
*/
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//Get the selected index. (The index param isn't
//always valid, so just use the value.)
int selectedIndex = ((Integer) value).intValue();
VO vo = numeros[selectedIndex];
if (isSelected) {
setText(vo.getId() + "");
setFont(list.getFont());
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setText(vo.getId() + "-" + vo.getDescription());
setFont(list.getFont());
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}
}