Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7431087
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T09:14:27+00:00 2026-05-29T09:14:27+00:00

i am trying to make a colored dropdown list with colored items (please see

  • 0

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();
            }
        });
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T09:14:28+00:00Added an answer on May 29, 2026 at 9:14 am

    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);
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

After trying to make a while(bool) loop and it failing because I couldn't see
Ok, I'm trying to make a program that finds the position of a colored
What I'm trying to make is a check list for a lotto game, which
I'm trying make this code which is from a Dictionary of Arrays (CODE) from
I am trying make long screen to vertical direction. So, I need a screen
Trying to make a make generic select control that I can dynamically add elements
Trying to make a MySQL-based application support MS SQL, I ran into the following
Trying to make a generic PL/SQL procedure to export data in specific XML format,
Trying to make a web service call to an HTTPS endpoint in my Silverlight
Trying to make a custom :confirm message for a rails form that returns data

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.