代码之家  ›  专栏  ›  技术社区  ›  downdrown

JavaFX TableView-将表格列的内容居中

  •  3
  • downdrown  · 技术社区  · 11 年前

    我有一个大问题。

    我试图将TableColumn的内容置于TableView的中心。

    我已经尝试了我在网上找到的所有东西,但真的没有效果!

    有人有同样的问题吗?有解决方案吗?

    希望得到帮助!

    编辑:

    我能够使用以下代码将静态单元格的内容居中:

    tc_customer.setCellFactory(new Callback<TableColumn<TvAccounting, String>, TableCell<TvAccounting, String>>() {
                    @Override
                    public TableCell<TvAccounting, String> call(TableColumn<TvAccounting, String> p) {
                        TableCell<TvAccounting, String> tc = new TableCell<TvAccounting, String>();
                        tc.setAlignment(Pos.CENTER);
                        tc.setText("SOMETEXT");
                        return tc;
                    }
                });
    

    但是内容应该来自数据库,我真的不知道如何从ObservableList对象中获取数据,我在 TABLEVIEWNAME.setItems 方法

    我第一次使用这个代码:

    tc_customer.setCellValueFactory(new PropertyValueFactory<TvAccounting, String>("Customer"));
    

    但没有办法将这些内容集中起来!

    有人能帮我吗?

    编辑:

    多亏了这个伟大的回答,我做到了!

    以下代码:

    tc_customer.setCellFactory(new Callback<TableColumn<TvAccounting, String>, TableCell<TvAccounting, String>>() {
                    @Override
                    public TableCell<TvAccounting, String> call(TableColumn<TvAccounting, String> p) {
                        TableCell<TvAccounting, String> tc = new TableCell<TvAccounting, String>(){
                            @Override
                            public void updateItem(String item, boolean empty) {
                                if (item != null){
                                    setText(item);
                                }
                            }
                        };
                        tc.setAlignment(Pos.CENTER);
                        return tc;
                    }
                });
    
                tc_customer.setCellValueFactory(new PropertyValueFactory<TvAccounting, String>("Customer"));
    

    非常感谢!!!

    1 回复  |  直到 11 年前
        1
  •  5
  •   Aerospace    10 年前

    CellValueFactory和CellFactory是两种不同的东西。 CellValueFactory用于指定值的来源,而CellFactory则指定如何显示这些值。

    同时使用两者。但在 setCellFactory 代码你应该 setText 。设置文本将由 TableCell 内部代码 updateItem() 方法此方法将使用“cellValueFactory”提供的值,并负责将其设置在自己的标签中。

    tc_customer.setCellFactory(
       new Callback< TableColumn<TvAccounting, String>,
                     TableCell<TvAccounting, String>>()
       {
          @Override public TableCell<TvAccounting, String>
          call(TableColumn<TvAccounting, String> p) {
             TableCell<TvAccounting, String> tc =
                new TableCell<TvAccounting, String>();
             tc.setAlignment(Pos.CENTER);
             // tc.setText("SOMETEXT"); This line should be removed
             return tc;
          }
       }
    );