1

这可能是一个重复 - 虽然我找不到它 - 我基本上只是尝试通过提供我自己的 ListCellRenderer 来自定义 JComboBox 显示:

targetCombo = new JComboBox();
targetCombo .setRenderer(new BasicComboBoxRenderer(){
    public Component getListCellRendererComponent(JList list, Object value, int index,              boolean isSelected, boolean cellHasFocus){
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value != null){
            MyObj myObj = (myObj)value;
            setText(myObj.getName());
        }
        return this;
    }
});

当我展开 JComboBox 列表时,组件会正确显示名称。但是,在选择项目时,显示将恢复为 myObj 的 toString() 值。

我错过了什么吗?

4

2 回答 2

4

替换使用BasicComboBoxRendererwithDefaultListCellRenderer

public class TestComboBox04 {

  public static void main(String[] args) {
    new TestComboBox04();
  }

  public TestComboBox04() {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
        }

        JComboBox targetCombo = new JComboBox();
        targetCombo.setRenderer(new DefaultListCellRenderer() {
          public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value != null) {
              MyObj myObj = (MyObj) value;
              setText(myObj.getName());
            }
            return this;
          }
        });
        targetCombo.addItem(new MyObj("A"));
        targetCombo.addItem(new MyObj("B"));
        targetCombo.addItem(new MyObj("C"));
        targetCombo.addItem(new MyObj("D"));

        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridBagLayout());
        frame.add(targetCombo);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

      }
    });
  }

  public class MyObj {

    private String name;

    public MyObj(String name) {
      this.name = name;
    }

    public String getName() {
      return name;
    }

  }

}

您永远不需要使用外观包中的组件,除非您计划创建自己的外观。

于 2013-01-21T22:16:16.093 回答
0

...显示恢复为 myObj 的 toString() 值。

除非您需要 toString() 特定的东西,否则覆盖它以返回“名称”,

那么你不需要渲染器 - 组合框将显示 toString() 值

于 2013-01-22T04:20:21.687 回答