Har*_*ter 6 java swing jlist defaultlistmodel
我有一个成分类
public class Ingredient {
String NameP;
List ListS;
String Desc;
List ListT;
...
Run Code Online (Sandbox Code Playgroud)
此类的多个实例存储在"对象"列表中.我也有一个
javax.swing.JList ListIng;
Run Code Online (Sandbox Code Playgroud)
随着它的模型设置为
ListIngModel = new DefaultListModel();
Run Code Online (Sandbox Code Playgroud)
我们的想法是使用Jlist显示所有对象的字段"NameP",选择其中一个进一步检查,然后抓取所选对象:
Ingredient Selected = ListIngModel.get(ListIng.getSelectedIndex())
Run Code Online (Sandbox Code Playgroud)
我可以在列表模型中加载对象,但然后JList显示那些对象的地址.是否有一种优雅的方式使它显示它存储的对象的属性?
你应该使用JList的CellRenderer
看看如何使用列表的更多细节.
基本上,它允许您定义列表模型中的给定对象在视图中的显示方式.此方法允许您根据需要自定义视图,甚至可以在运行时替换它.
例如
public class IngredientListCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList<?> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof Ingredient) {
Ingredient ingredient = (Ingredient)value;
setText(ingredient.getName());
setToolTipText(ingredient.getDescription());
// setIcon(ingredient.getIcon());
}
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6756 次 |
| 最近记录: |