TableCell not applied consistently

2019-09-07 13:14发布

When running the program below, the TableCell is not applied (the numbers are left aligned instead of right aligned). Clicking on the "Change Values" button corrects the alignment.

Using jdk1.8.0-ea-b114

Am I missing anything obvious or is it a bug?

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条回答
冷血范
2楼-- · 2019-09-07 13:56
霸刀☆藐视天下
3楼-- · 2019-09-07 14:04
登录 后发表回答