Hi
I am having trouble rendering a combo box with icon near the text. Below is a simple code which demonstrates my problem.
import java.awt.Component;
import java.util.HashMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
public class IconComboBox extends javax.swing.JDialog {
private JComboBox jComboBox1;
private String[] modelData;
private HashMap<String, Icon> icons = new HashMap<String, Icon>();
/** Creates new form IconComboBox */
public IconComboBox(java.awt.Frame parent, boolean modal) {
super(parent, modal);
ImageIcon img1 = new ImageIcon("1.png");
ImageIcon img2 = new ImageIcon("2.png");
modelData = new String[] { "Item 1", "Item 2", "Item 3", "Item 4" };
icons.put(modelData[0],img1);
icons.put(modelData[1],img1);
icons.put(modelData[2],img2);
icons.put(modelData[3],img2);
initComponents();
}
private void initComponents()
{
jComboBox1 = new javax.swing.JComboBox();
getContentPane().setLayout(new java.awt.FlowLayout());
setDefaultCloseOperation(javax.swing.WindowConstan ts.DISPOSE_ON_CLOSE);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(modelData));
getContentPane().add(jComboBox1);
jComboBox1.setRenderer(new TypeListCellRenderer(icons));
setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
pack();
}
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAn dFeelClassName());
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new IconComboBox(new javax.swing.JFrame(), true).setVisible(true);
}
});
}
catch (Exception e) {
// handle exception
}
}
private class TypeListCellRenderer extends JLabel implements ListCellRenderer {
HashMap<String, Icon> icons;
public TypeListCellRenderer(HashMap<String, Icon> icons) {
super();
this.icons = icons;
}
public Component getListCellRendererComponent( JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus ) {
String type = (String) value;
setText( type );
setIcon( icons.get( type ) );
return this;
}
}
}
When i run this program i will see the combo box with only the icon displayed (no text).
Now if will remark the following line:
UIManager.setLookAndFeel(UIManager.getSystemLookAn dFeelClassName());
Then the code works just fine.
Did someone knows how to solve this look and feel issue ?