How can we set the foreground and background color to JComboBox items in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JComboBox is a subclass of JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value. A JComboBox can generate an ActionListener, ChangeListener and ItemListener interfaces when the user actions on a combo box. We can also set the foreground and background color to JComboBox items by using setForeground() and setBackground() methods of a JComboBox class.

Example

import java.awt.*;
import javax.swing.*;
public class JComboBoxItemColorTest extends JFrame{
   private JComboBox jcb;
   public JComboBoxItemColorTest() {
      setTitle("JComboBoxItemColor Test");
      String[] countries = {"India", "Australia", "England", "South Africa", "Newzealand"};
      jcb = new JComboBox(countries);
      jcb.setForeground(Color.blue);
      jcb.setBackground(Color.white);
      add(jcb, BorderLayout.NORTH);
      setSize(500,300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[]args) {
      new JComboBoxItemColorTest();
   }
}

Output

raja
Published on 23-Jul-2019 22:18:27
Advertisements