JavaFx:使用ObservableMap填充TableView

时间:2014-12-02 05:30:26

标签: map javafx tableview

我在互联网上找到了正确的答案,我如何用ObservableMap填充tableviw作为MapProperty。我想在tableview中显示按值排序的文章。

public class Article {

    private MapProperty<String, Integer> article = new SimpleMapProperty<>(); 


        public final ObservableMap<String, Integer> geArticle() {
            return article.get();
        }

        public final void setArticle(ObservableMap<String, Integer> value) {
            article.set(value);
        }

        public MapProperty<String, Integer> articleProperty() {
            return article;
        }
    }

 public class TableController extends VBox implements Initializable{

    @FXML private TableView<Article> tableView;
    @FXML private TableColumn<Article, String> article;
    @FXML private TableColumn<Article, Integer> count;

    ......

    @Override
        public void initialize(URL location, ResourceBundle resources) {
            article.setCellValueFactory(new PropertyValueFactory<Article, String>("article"));
            count.setCellValueFactory(new PropertyValueFactory<Article, Integer>("count"));
    }
  }

1 个答案:

答案 0 :(得分:0)

执行此操作的一种简单方法是循环遍历keySet并创建文章列表:

ObservableList<Article> list =  FXCollections.observableArrayList();

    for(String key : article.keySet()){
        Article art = new Article(key, article.get(key));
        list.add(art);
    }

然后将表项设置为list

如果您想对列表进行排序,请在文章中进行比较,并使用collections.sort(list);

public class Article implements Comparable<Article> {
       //...
        public int compareTo(Article compareArticle ) {

              //ascending order
              return this.value - compareArticle.getValue();
        }

    }