ListView中显示自定义类型对象的某一个属性
2016-04-04JavaFX攻城狮4263°c
A+ A-
官方给出的创建一个ListView的方法如下:
ObservableList<String> names = FXCollections.observableArrayList( "Julia", "Ian", "Sue", "Matthew", "Hannah", "Stephan", "Denise"); ListView<String> listView = new ListView<String>(names);
用这种方式创建出来的ListView,其item是由String类型的字符串直接填充出来的,这个不难理解,可是如果要在ListView里面显示自定义对象的某个属性要怎么做呢?经过我的研究,解决方法如下:
首先定义自定义类型(即实体类):
public class DirType { private final StringProperty dirId; private final StringProperty dirName; private final ObjectProperty<LocalDate> createTime; public DirType(String dirId,String dirName){ this.dirId=new SimpleStringProperty(dirId); this.dirName=new SimpleStringProperty(dirName); Calendar date=Calendar.getInstance(); this.createTime=new SimpleObjectProperty<LocalDate>(LocalDate.of(date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DAY_OF_MONTH))); } public String getDirId(){ return dirId.get(); } public void setDirId(String dirId){ this.dirId.set(dirId); } public StringProperty dirIdProperty(){ return dirId; } public String getDirName(){ return dirName.get(); } public void setDirName(String dirName){ this.dirName.set(dirName); } public StringProperty dirNameProperty(){ return dirName; } public LocalDate getCreateTime(){ return createTime.get(); } public void setCreateTime(LocalDate createTime){ this.createTime.set(createTime); } public ObjectProperty<LocalDate> createTimeProperty(){ return createTime; } }
然后在Controller初始化方法里面为ListView进行项目填充,在Controller中添加ListView的定义:
@FXML private ListView<DirType> classType;
添加ListView填充项定义的集合:
private ObservableList<DirType> items=FXCollections.observableArrayList();
然后在初始化方法里面进行初始化操作:
@FXML private void initialize(){ items.add(new DirType(CommonCore.getId(), "常规")); items.add(new DirType(CommonCore.getId(), "游戏")); items.add(new DirType(CommonCore.getId(), "邮箱")); items.add(new DirType(CommonCore.getId(), "登录")); items.add(new DirType(CommonCore.getId(), "公司")); classType.setItems(items); //为ListView添加格式化方式为每个对象的dirName属性 classType.setCellFactory(new Callback<ListView<DirType>, ListCell<DirType>>() { @Override public ListCell<DirType> call(ListView<DirType> arg0) { // TODO Auto-generated method stub return new ListCell<DirType>(){ public void updateItem(DirType item,boolean empty){ super.updateItem(item, empty); if(item!=null&&!empty){ this.setText(item.getDirName()); } } }; } }); }
这样做好后,在列表中显示出来的就是自定义对象的dirName属性值,效果如下:
编辑时间:2016年4月4日11:00:05
标签:javafx