Инициализировать столбец таблицы на основе нажатия кнопки - PullRequest
0 голосов
/ 07 июня 2018

Я довольно новичок в JavaFX.У меня есть таблица с несколькими столбцами и двумя кнопками (btnBuilding, btnBSearch) вне таблицы.В таблице у меня есть столбец colAction, в котором я хочу, чтобы некоторые кнопки основывались на кнопке, нажатой за пределами таблицы.Предположим, что если я нажму btnBuilding, я хочу иметь 2 кнопки Save и Refresh в моем столбце colAction и всякий раз, когда я нажимаю btnBSearch, я хочу иметь 2 кнопки Edit и Add в моем colAction столбец.Внутри initialize() я попробовал, как показано ниже

colAction.setCellFactory(col -> {
                Button SaveButton = new Button("Save");
                Button AddButton = new Button("Add");
                Button RefreshButton = new Button("Refresh");
                Button EditButton = new Button("Edit");
              HBox hbox = new HBox(5);
               if(btnBSearch.isFocused())
               hbox.getChildren().addAll(AddButton,EditButton);
               else if(btnBuilding.isFocused())
                   hbox.getChildren().addAll(SaveButton,RefreshButton);


                TableCell<ModelBrBuilding, ModelBrBuilding> cell = new TableCell<ModelBrBuilding, ModelBrBuilding>() {
                    @Override
                    //Updating with the number of row 
                    public void updateItem(ModelBrBuilding building, boolean empty) {
                        super.updateItem(building, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(hbox);
                        }
                    }

                };

                EditButton.setOnAction((ActionEvent event)->{               
                });

                RefreshButton.setOnAction(event->{          
                });

                SaveButton.setOnAction((ActionEvent event) -> {                     
                });
                AddButton.setOnAction(event -> {                                  
                    });

                return cell ;
            });

Но проблема в том, какую кнопку я нажимаю, я всегда получаю Add и Edit в своем столбце действий.Как я могу добавить другую кнопку в моем столбце в зависимости от кнопки (находится вне таблицы), которую я нажимаю?

Ответы [ 2 ]

0 голосов
/ 07 июня 2018

cellFactory выполняется только один раз для каждой ячейки.Вы должны убедиться, что ячейка обновлена, когда нажимается кнопка за пределами таблицы.

Это можно сделать, создав свойство, содержащее фабрику для graphic s, и прослушайте его.

public interface GraphicFactory<T> {

    Node createGraphic();

    void updateGraphic(Node graphic, T item);
}
public class ReplacableGraphicTableCell<S, T> extends TableCell<S, T> {

    private final ChangeListener<GraphicFactory<T>> factoryListener = (o, oldValue, newValue) -> {
        if (newValue == null || isEmpty()) {
            setGraphic(null);
        } else {
            Node n = newValue.createGraphic();
            newValue.updateGraphic(n, getItem());
            setGraphic(n);
        }
    };

    private final ObservableValue<GraphicFactory<T>> factory;

    private ReplacableGraphicTableCell(ObservableValue<GraphicFactory<T>> factory) {
        this.factory = factory;
        factory.addListener(factoryListener);
    }

    public static <E, F> Callback<TableColumn<E, F>, TableCell<E, F>> forTableColumn(ObservableValue<GraphicFactory<F>> factory) {
        if (factory == null) {
            throw new IllegalArgumentException();
        }
        return column -> new ReplacableGraphicTableCell(factory);
    }

    @Override
    protected void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setGraphic(null);
        } else {
            GraphicFactory<T> fact = factory.getValue();
            if (fact == null) {
                setGraphic(null);
            } else {
                Node graphic = getGraphic();
                if (graphic == null) {
                    graphic = fact.createGraphic();
                    setGraphic(graphic);
                }

                fact.updateGraphic(graphic, item);
            }
        }
    }

}
final ObjectProperty<GraphicFactory<Item>> graphicFactory = new SimpleObjectProperty<>();
TableColumn<Item, Item> column = new TableColumn<>();
column.setCellValueFactory(cd -> new SimpleObjectProperty<>(cd.getValue()));
column.setCellFactory(ReplacableGraphicTableCell.forTableColumn(graphicFactory));

ToggleGroup tg = new ToggleGroup();
tg.selectedToggleProperty().addListener((o, oldValue, newValue) -> {
    GraphicFactory<Item> factory = null;
    if (newValue != null) {
        factory = (GraphicFactory<Item>) newValue.getUserData();
    }
    graphicFactory.set(factory);
});
RadioButton rb = new RadioButton("Add/Edit");
rb.setUserData(new GraphicFactory<Item>() {

    @Override
    public Node createGraphic() {
        Button add = new Button("Add");
        Button edit = new Button("Edit");

        HBox hbox = new HBox(add, edit);
        add.setOnAction(evt -> {
            System.out.println("Add " + hbox.getUserData());
        });
        edit.setOnAction(evt -> {
            System.out.println("Edit " + hbox.getUserData());
        });
        return hbox;
    }

    @Override
    public void updateGraphic(Node graphic, Item item) {
        graphic.setUserData(item);
    }

});
rb.setToggleGroup(tg);

RadioButton rb2 = new RadioButton("Save/Refresh");
rb2.setUserData(new GraphicFactory<Item>() {

    @Override
    public Node createGraphic() {
        Button save = new Button("Save");
        Button refresh = new Button("Refresh");

        HBox hbox = new HBox(save, refresh);
        save.setOnAction(evt -> {
            System.out.println("Save " + hbox.getUserData());
        });
        refresh.setOnAction(evt -> {
            System.out.println("Refresh " + hbox.getUserData());
        });
        return hbox;
    }

    @Override
    public void updateGraphic(Node graphic, Item item) {
        graphic.setUserData(item);
    }

});
rb2.setToggleGroup(tg);
0 голосов
/ 07 июня 2018

Так работать не будет.Для начала вам нужно обработать кнопки btnBuilding и btnBSearch.Какая из нажатых кнопок должна отражаться в используемой вами таблице.Для этой цели можно создать одну функцию, отражающую, какая из двух кнопок нажата.

BooleanProperty showSearch = new SimpleBooleanProperty(false);
...
btnBuilding.setOnAction(e -> showSearch.setValue(false));
btnBSearch.setOnAction(e -> showSearch.setValue(true));

Затем вы связываете столбец colAction со значением свойства.

colAction.setCellValueFactory(cdf -> showSearch);

В этой ситуации вы можете создать CellFactory, чтобы создать ячейку динамического содержимого

colAction.setCellFactory(col -> {
    return new TableCell<String, Boolean>() {
        Button SaveButton = new Button("Save");
        Button AddButton = new Button("Add");
        Button RefreshButton = new Button("Refresh");
        Button EditButton = new Button("Edit");

        HBox hboxBuilding = new HBox(5);
        HBox hboxSearch = new HBox(5);

        {
            hboxBuilding.getChildren().addAll(AddButton,EditButton);
            hboxSearch.getChildren().addAll(SaveButton,RefreshButton);
        }

        @Override
        protected void updateItem(Boolean item, boolean empty) {
            super.updateItem(item, empty);

            if (empty) {
                setGraphic(null);
            }
            else {
                setGraphic(item ? hboxBuilding : hboxSearch);
            }
        }
    };
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...