【问题标题】:Java JList unwanted toString() conversionJava JList 不需要的 toString() 转换
【发布时间】:2012-03-05 01:05:12
【问题描述】:

我扩展的我的 JList 让用户拖放重新排序它(使用 Reorder a JList with Drag-and-DropUse drag and drop to reorder a list)但它给了我一个奇怪的结果。它没有给我我的自定义JComponent,而是给了我它的.toString() 值。我将自定义JList 的模型设置为DefaultListModel<JComponent>,认为它可以工作,但它没有。

【问题讨论】:

  • 那些文章严重过时了——目前自定义dnd的方式是自定义TransferHandler,见docs.oracle.com/javase/tutorial/uiswing/index.html对应章节
  • 刚刚注意到:您从来没有(99.99%)在列表中有 JComponent 类型的项目。
  • 澄清@kleopatra 的评论。您的ListModel 中没有JComponent 实例。但是让渲染器创建自定义JComponents 来表示您的模型项是完全可以接受的
  • @kleopatra 我尝试根据需要更改文章,例如将模型更改为 DefaultListModel<_JComponent_> 并添加真正的 JComponents。

标签: java string swing drag-and-drop jlist


【解决方案1】:

您需要为要渲染的对象创建自定义CellRenderer。默认情况下,JList 会显示组件的 toString 值(因为 DefaultListCellRenderer 扩展了 JLabel)。

class MyRenderer extends DefaultListCellRenderer {
   public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      Component c = super.getListCellRendererComponent(...);
      setText(getValue(value)); // where getValue is some method you implement that gets the text you want to render for the component
      return c;
}

如果您实际上不想渲染字符串,请创建 CellRenderer 的实现,该实现返回您要渲染的组件。

【讨论】:

  • 所以我想我在扩展我的 JComponent 并让 getListCellRendererComponent() 返回我的 JComponent 时实现了CellRenderer?我会试试看。谢谢:)。
猜你喜欢
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 2012-05-06
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2021-05-17
相关资源
最近更新 更多