| Author |
JComboBox with muticolor items??
|
Sajee Joseph
Ranch Hand
Joined: Jan 17, 2001
Posts: 200
|
|
Hi, I have a JComboBox which displays a set of names like "Sam","Saj","Jane"..... and so on. Now depending on some condition i need the names in the JComboBox to have different colors. I need just 2 colors. How do i do that. Code exampples will be helpful Waiting for ur replies Regards Saj
|
 |
john mattucci
Ranch Hand
Joined: Nov 03, 2000
Posts: 331
|
|
This answer was given to me several weeks back and it should also answer your question You have to write your own ListCellRenderer and a data class. That is for instance extend JLabel and implement the appropriate interface. Please take a look at the api documentation of the ListCellRenderer interface. The only to implement method is public Component getListCellRendererComponent(...) So you have to define your data class, for instance: public class MyData { private String mDescription = "default"; public String getDescription() { return mDescription; } public void setDescription(String description) { mDescription = description != null ? description : "default"; } } and define the cell renderer: class MyDataCellRenderer extends JLabel implements ListCellRenderer { public MyDataCellRenderer() { setOpaque(true); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof MyData) { MyData myData = (MyData) value; setText(myData.getDescription()); if (myData.isCompleted()) { if (isSelected) { // change the colors to the desired: setBackground(list.getSelectionBackground()); setForeground(Color.red); } else { // change the colors to the desired: setBackground(list.getBackground()); setForeground(Color.red); } } else { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } } } return this; } } Finally you have to make your ListCellRenderer the cell renderer of the JList: myJList.setCellRenderer(...); and you add elements of MyData to the JList... You can find another example in the api documentation of JList... Good luck Tom
|
 |
 |
|
|
subject: JComboBox with muticolor items??
|
|
|