Reputation: 93
Is it possible to switch the row position in a TableView
in javafx.
Suppose I created a 5 rows and and there is two button as "UP" and "DOWN". On click of UP button user can swap the particular selected row to upward direction and for DOWN button user can move the row to downward position on click of DOWN button; i.e. user can place the particlar selected row to any position in TableView
using Button
clicks. Is that possible in TableView
using javafx? If its possible kindly provide me a logic to do that.
Upvotes: 2
Views: 1878
Reputation: 82461
You can simply modify the items
of the TableView
to achieve this effect:
@Override
public void start(Stage primaryStage) {
TableView<Item<String>> tableView = createTableView();
Button upButton = new Button("Up");
Button downButton = new Button("Down");
ReadOnlyIntegerProperty selectedIndex = tableView.getSelectionModel().selectedIndexProperty();
upButton.disableProperty().bind(selectedIndex.lessThanOrEqualTo(0));
downButton.disableProperty().bind(Bindings.createBooleanBinding(() -> {
int index = selectedIndex.get();
return index < 0 || index+1 >= tableView.getItems().size();
}, selectedIndex, tableView.getItems()));
upButton.setOnAction(evt -> {
int index = tableView.getSelectionModel().getSelectedIndex();
// swap items
tableView.getItems().add(index-1, tableView.getItems().remove(index));
// select item at new position
tableView.getSelectionModel().clearAndSelect(index-1);
});
downButton.setOnAction(evt -> {
int index = tableView.getSelectionModel().getSelectedIndex();
// swap items
tableView.getItems().add(index+1, tableView.getItems().remove(index));
// select item at new position
tableView.getSelectionModel().clearAndSelect(index+1);
});
BorderPane root = new BorderPane(tableView);
root.setRight(new VBox(10, upButton, downButton));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
Upvotes: 5