import java.awt.Component; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.geom.Rectangle2D; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; public class ComboBoxRenderer extends JLabel implements ListCellRenderer { /** * */ // private static final long serialVersionUID = 1L; private Dimension d = null; private JComboBox box; private JLabel labelToInsert = null; public ComboBoxRenderer(JComboBox box) { setOpaque(true); setHorizontalAlignment(LEFT); setVerticalAlignment(CENTER); this.box = box; calculateWidth(); } public void setLabelToInsert(JLabel l){ this.labelToInsert = l; } private void calculateWidth(){ FontMetrics fm = box.getFontMetrics(box.getFont()); int i = 0; int y= 0; for(int temp = 0; temp < box.getItemCount();temp++){ String st = (String) box.getItemAt(temp); Rectangle2D rect = fm.getStringBounds(st,this.getGraphics()); if(rect.getWidth() > i) i = (int) rect.getWidth(); y= (int)rect.getHeight(); } d =new Dimension(i+20,y); } public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setText((String)value); this.setMinimumSize(d); this.setPreferredSize(d); this.setMaximumSize(d); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); if(labelToInsert != null) labelToInsert.setText(this.getText()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } return this; } }