简体   繁体   English

如何为JComboBox中的项目分配不同的颜色?

[英]How to assign different colors to items in JComboBox?

I have a JComboBox and have 10 string items added in it. 我有一个JComboBox,并添加了10个字符串项。 I want to assign different colors to each item. 我想为每个项目分配不同的颜色。 How i can achive this? 我怎么能做到这一点? Please help. 请帮忙。

The example in Chandru's answer looks like a lot of code so I can understand why you're asking for an easier solution. Chandru的答案中的示例看起来像很多代码,因此我可以理解为什么要求更简单的解决方案。 However, if you subclass DefaultListCellRenderer a lot of the work is done for you, as this renderer is a subclass of JLabel . 但是,如果您DefaultListCellRenderer ,则会为您完成大量工作,因为此渲染器是JLabel的子类。

JList list = ... // Create JList

// Install custom renderer.
list.setCellRenderer(new DefaultListCellRenderer() {
  public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

    // Request superclass to render the JLabel.
    Component ret = super.getListCellRenderer(list, value, index, isSelected, cellHasFocus);

    // Now conditionally override background if cell isn't selected.
    if (!isSelected) {
      String s = String.valueOf(value);

      if (s.equals("Foo")) {
        ret.setBackground(Color.RED);
      } else {
        ret.setBackground(Color.GREEN);
      }
    }

    return ret;
  }
});

You must use a custom list cell renderer. 您必须使用自定义列表单元格渲染器。 Look into this how-to for an example. 请查看示例的示例。

You must implement a new ListCellRenderer ,which will be used by your combobox, through setRenderer , to render properly your objects. 您必须实现一个新的ListCellRenderer ,组合框将通过setRenderer使用它来正确渲染对象。

You can extend BasicComboBoxRenderer to avoid reconding everything. 您可以扩展BasicComboBoxRenderer以避免重新协调所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM