Java JComboBox外观

时间:2014-03-12 15:46:33

标签: java swing jcombobox

在我的应用程序中,我有两种JComboBox:可编辑且不可编辑 以下是使用Java 7在Windows 7中显示可编辑的方式:

enter image description here

这里是不可编辑的:

enter image description here

是否可以在不可编辑的JComboBox

中设置白色背景

1 个答案:

答案 0 :(得分:0)

只需在不可编辑的组合上设置背景。 注意:默认情况下,可编辑组合的编辑器为JTextField,这就是使用UIManager值的原因。

在Windows XP上使用Java 7:

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;

public class ComboBoxDemo implements Runnable
{
  public static void main(String[] args) throws Exception
  {
    SwingUtilities.invokeLater(new ComboBoxDemo());
  }

  @SuppressWarnings("unchecked")
  public void run()
  {
    String[] items = new String[]{"", "Apple", "Banana", "Carrot"};

    Color bgColor = UIManager.getColor("TextField.background");

    UIManager.put("ComboBox.selectionBackground",
                  new ColorUIResource(bgColor));

    JComboBox combo1 = new JComboBox(items);
    combo1.setPrototypeDisplayValue("XXXXXXXXXXXXXXX");
    combo1.setEditable(true);
    combo1.setSelectedIndex(-1);

    JComboBox combo2 = new JComboBox(items);
    combo2.setPrototypeDisplayValue("XXXXXXXXXXXXXXX");
    combo2.setEditable(false);
    combo2.setSelectedIndex(-1);
    combo2.setBackground(bgColor);

    JFrame frame = new JFrame();
    Container c = frame.getContentPane();
    c.setLayout(new FlowLayout());
    c.add(combo1);
    c.add(combo2);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 100);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

编辑添加了代码以消除大小和焦点颜色的差异。

相关问题