Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colored jcombobox with colored items and focus

i am trying to make a colored dropdown list with colored items (please see code below). The color is getting applied after the combobox loses focus.

is this correct behaviour?

how can i get the foreground and/or the background color to change when the combobox has the focus?

thanks

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class DropDown {
    enum Colors {
        red(Color.red), orange(Color.orange), green(Color.green), yellow(Color.yellow), blue(Color.blue);
        Colors(Color color) {
            this.color = color;
        }
        static String[] listModel() {
            java.util.List<Colors> values = Arrays.asList(values());
            String s = values.toString().replaceAll(" ", "");
            return s.substring(1, s.length() - 1).split(",");
        }
        final Color color;
    }
    static class ColoredCellRenderer implements ListCellRenderer {
        protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
        private final static Dimension preferredSize = new Dimension(0, 20);
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected,
                    cellHasFocus);
            if (index != -1) if (value instanceof String) renderer.setForeground(Colors.valueOf((String) value).color);
            else
                System.out.println("not a string");
            else
                System.out.println("in getListCellRendererComponent, index=-1");
            renderer.setPreferredSize(preferredSize);
            return renderer;
        }
    }
    private static JComboBox addLabeledComboBox(Container c, String label, String[] model) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        Border border = BorderFactory.createLineBorder(Color.green, 1);
        panel.setBorder(border);
        JLabel l = new JLabel(label);
        panel.add(l);
        final JComboBox comboBox = new JComboBox(model);
        comboBox.setName(label);
        l.setLabelFor(comboBox);
        comboBox.setRenderer(new ColoredCellRenderer());
        panel.add(comboBox);
        c.add(panel);
        return comboBox;
    }
    private static void addContent(Container c) {
        c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
        ActionListener actionListener = new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                if (e.getSource() instanceof JComboBox) {
                    final JComboBox comboBox = (JComboBox) e.getSource();
                    Object selected = comboBox.getSelectedItem();
                    String string = (String) selected;
                    Color color = Colors.valueOf(string).color;
                    int i = comboBox.getSelectedIndex();
                    if (i != -1) {
                        System.out.println("comboBox " + comboBox.getName() + " " + color);
                        comboBox.setForeground(color);
                        System.out.println(comboBox.hasFocus());
                        // comboBox.repaint();
                    } else
                        System.out.println("in actionListener selected=" + selected);
                } else
                    System.out.println("in actionListener selected is not a comboBox");
            }
        };
        c.add(new JButton("button"));
        for (int i = 0; i < 2; i++) {
            JPanel panel = new JPanel();
            Border border = BorderFactory.createLineBorder(Color.red, 1);
            panel.setBorder(border);
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            panel.add(new JLabel("label " +(i+1)));
            JComboBox comboBox = addLabeledComboBox(panel, "" + (i + 1), Colors.listModel());
            comboBox.addActionListener(actionListener);
            comboBox.setSelectedIndex(0); // select something
            c.add(panel);
        }
    }
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Colored JComboBox");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addContent(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @SuppressWarnings("synthetic-access") public void run() {
                createAndShowGUI();
            }
        });
    }
}
like image 951
Ray Tayek Avatar asked Dec 18 '25 23:12

Ray Tayek


1 Answers

Here is another approach:

//JList#setSelectionForeground(...) version
static class ColoredCellRenderer implements ListCellRenderer {
  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
  private final Color selectionBackground = new Color(240,200,200);
  public Component getListCellRendererComponent(
      JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    Color fgc = Colors.valueOf((String)value).color;
    if(index<0) {
      //comboBox.setForeground(fgc); //Windows, CDE/Motif Look & Feel
      list.setSelectionForeground(fgc);
      list.setSelectionBackground(selectionBackground);
    }
    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(
        list, value, index, isSelected, cellHasFocus);
    if (index != -1) {
      renderer.setForeground(fgc);
    }
    return renderer;
  }
}

//html version
static class ComboHtmlRenderer extends DefaultListCellRenderer {
  private final Color selectionBackground = new Color(240,200,200);
  @Override public Component getListCellRendererComponent(
      JList list, Object value, int index, boolean isSelected, boolean hasFocus) {
    Color fgc = Colors.valueOf((String)value).color;
    if(index<0) {
      list.setSelectionBackground(selectionBackground);
    }
    JLabel l = (JLabel)super.getListCellRendererComponent(
                 list, value, index, isSelected, hasFocus);
    l.setText("<html><font color="+hex(fgc)+">"+value);
    l.setBackground(isSelected?selectionBackground:list.getBackground());
    return l;
  }
  private static String hex(Color c) {
    return String.format("#%06x", c.getRGB()&0xffffff);
  }
}
like image 144
aterai Avatar answered Dec 21 '25 12:12

aterai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!