如何在 Java 中設定 JComboBox 項的前景色和背景色?


一個 JComboBox JComponent 類的子類,它是 文字域 下拉列表的組合,使用者可以從中選擇一個值。當用戶在組合框上執行操作時,一個 JComboBox 可以生成 ActionListener、ChangeListener 和 ItemListener 介面。我們還可以使用 JComboBox 類的 setForeground() setBackground() 方法來設定 JComboBox 項的前景色和背景色。

示例

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();
   }
}

輸出

更新於:10-2-2020

2K+ 瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.