Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use a <code>ListCellRenderer</code>. You need to write custom class for this. Here is the full code to set foreground based on index (to avoid duplicates). You can also set custom selection background and background for this. See the comments in the code.</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; class ListCellRendererDemo2 extends JFrame { Hashtable&lt;Integer,Color&gt; table; JComboBox&lt;String&gt; c; public ListCellRendererDemo2() { createAndShowGUI(); } private void createAndShowGUI() { setTitle("JComboBox Demo"); setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); table=new Hashtable&lt;Integer,Color&gt;(); table.put(1,Color.RED); table.put(2,Color.BLUE); table.put(3,Color.GREEN); table.put(4,Color.GRAY); c=new JComboBox&lt;String&gt;(); c.addItem("Item 1"); c.addItem("Item 2"); c.addItem("Item 3"); c.addItem("Item 4"); c.addItem("Item 5"); c.addItem("Item 6"); c.addItem("Item 7"); c.addItem("Item 8"); c.setRenderer(new MyListCellRenderer(table)); add(c); setSize(400,400); setVisible(true); } public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable(){ public void run() { new ListCellRendererDemo2(); } }); } } class MyListCellRenderer extends DefaultListCellRenderer { Hashtable&lt;Integer,Color&gt; table; public MyListCellRenderer(Hashtable&lt;Integer,Color&gt; table) { this.table=table; // Set opaque for the background to be visible setOpaque(true); } public Component getListCellRendererComponent(JList jc,Object val,int idx,boolean isSelected,boolean cellHasFocus) { // Set text (mandatory) setText(val.toString()); // Set the foreground according to the selected index setForeground(table.get(idx)); // Set your custom selection background, background // Or you can get them as parameters as you got the table if(isSelected) setBackground(Color.LIGHT_GRAY); else setBackground(Color.WHITE); return this; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload