TableCell未始终如一地应用

时间:2013-11-12 00:19:53

标签: java javafx-2 javafx javafx-8

运行下面的程序时,不会应用TableCell(数字左对齐而不是右对齐)。单击“更改值”按钮可更正对齐方式。

使用jdk1.8.0-ea-b114

我是否遗漏了任何明显的或是错误的?

import java.util.Arrays;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

public class TestFX extends Application {

    public static void main(String[] args) {
        launch(TestFX.class);
    }

    @Override
    public void start(final Stage stage) throws Exception {
        MyTable table = new MyTable();
        table.table.getItems().addAll(Arrays.asList(new Item(0), new Item(1), new Item(-1)));

        Scene scene = new Scene(table);

        stage.setScene(scene);
        stage.show();
    }

    static class MyTable extends VBox {

        private final Button button = new Button("Change Values");
        private final TableView<Item> table = new TableView<>();

        MyTable() {
            super();
            TableColumn<Item, Double> value = new TableColumn<>("Value");
            value.setCellValueFactory(new PropertyValueFactory<>("value"));
            value.setCellFactory((p) -> new NumberTableCell<>());

            table.getColumns().add(value);

            button.setOnMouseClicked(this::changeValues);
            getChildren().addAll(button, table);
        }

        public void changeValues(MouseEvent e) {
            for (Item i : table.getItems()) {
                i.value.set(i.value.get() + 1);
            }
        }
    }

    public static class Item {
        private final DoubleProperty value;
        public Item(double value) { this.value = new SimpleDoubleProperty(value); }
        public DoubleProperty valueProperty() { return value; }
    }

    static class NumberTableCell<T> extends TableCell<T, Double> {
        @Override
        protected void updateItem(Double item, boolean empty) {
            super.updateItem(item, empty);
            if (empty || item == null) {
                setText(null);
                setTextFill(null);
            } else {
                setText(String.valueOf(item));
                setAlignment(Pos.CENTER_RIGHT);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

参考object.your代码没问题。

试试这个...我希望它为你工作。

https://stackoverflow.com/questions/17264929/how-to-change-the-row-color-based-on-data-that-can-change-in-a-tableview

答案 1 :(得分:0)

这是一个关于jira的错误:https://javafx-jira.kenai.com/browse/RT-34237