JavaFXでTableViewのMenuButtonを書き換えるサンプルコード
サンプルコード:
public class TableViewTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage paramStage) throws Exception {
final ObservableList data = FXCollections.observableArrayList(
new Person(1, “山田", 23), new Person(2, “豊田", 24), new Person(3,
“山崎", 56));
final TableView tableView = new TableView();
tableView.setTableMenuButtonVisible(true);
TableColumn<Person, Integer> idColumn = new TableColumn<Person, Integer>(
“id");
idColumn.setCellValueFactory(new PropertyValueFactory<Person, Integer>(
“num"));
CheckMenuItem showHideidCol = new CheckMenuItem(“id");
showHideidCol.selectedProperty().bindBidirectional(
idColumn.visibleProperty());
TableColumn<Person, String> nameColumn = new TableColumn<Person, String>(
“名前");
nameColumn
.setCellValueFactory(new PropertyValueFactory<Person, String>(
“name"));
CheckMenuItem showHideNameCol = new CheckMenuItem(“name");
showHideNameCol.selectedProperty().bindBidirectional(
nameColumn.visibleProperty());
TableColumn<Person, Integer> ageColumn = new TableColumn<Person, Integer>(
“年齢");
ageColumn
.setCellValueFactory(new PropertyValueFactory<Person, Integer>(
“age"));
CheckMenuItem showHideAgeCol = new CheckMenuItem(“age");
showHideAgeCol.selectedProperty().bindBidirectional(
ageColumn.visibleProperty());
tableView.getColumns().addAll(idColumn, nameColumn, ageColumn);
tableView.setItems(data);
BorderPane root = new BorderPane();
ScrollPane scroller = new ScrollPane();
scroller.setContent(tableView);
root.setCenter(scroller);
Scene scene = new Scene(root, 500, 250);
paramStage.setScene(scene);
paramStage.centerOnScreen();
paramStage.show();
final ContextMenu menu = new ContextMenu();
menu.getItems().addAll(showHideNameCol, showHideAgeCol);
final Node showHideColumnsButton = tableView
.lookup(“.show-hide-columns-button");
EventHandler mousePressedHandler = new EventHandler() {
@Override
public void handle(MouseEvent event) {
if (menu.isShowing()) {
menu.hide();
} else {
menu.show(showHideColumnsButton, Side.BOTTOM, 0, 0);
}
event.consume();
}
};
showHideColumnsButton.addEventFilter(MouseEvent.MOUSE_PRESSED,
mousePressedHandler);
}
public static class Person {
private final SimpleIntegerProperty num;
private final SimpleStringProperty name;
private final SimpleIntegerProperty age;
private Person(int id, String name, int age) {
this.name = new SimpleStringProperty(name);
this.age = new SimpleIntegerProperty(age);
this.num = new SimpleIntegerProperty(id);
}
public Integer getNum() {
return num.getValue();
}
public String getName() {
return name.get();
}
public Integer getAge() {
return age.getValue();
}
}
}