Context Menu on a row of TableView?

后端 未结 3 1802
北荒
北荒 2021-02-05 18:46

I am using JavaFX and my application has a table and I can add elements to the table but I want to create a context menu that displays on a row when I right click on that row.

相关标签:
3条回答
  • 2021-02-05 18:51

    JavaFX 8 (with Lambda):

    MenuItem mi1 = new MenuItem("Menu item 1");
    mi1.setOnAction((ActionEvent event) -> {
        System.out.println("Menu item 1");
        Object item = table.getSelectionModel().getSelectedItem();
        System.out.println("Selected item: " + item);
    });
    
    ContextMenu menu = new ContextMenu();
    menu.getItems().add(mi1);
    table.setContextMenu(menu);
    

    See also: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ContextMenu.html

    0 讨论(0)
  • 2021-02-05 18:55

    I believe that the best solution would be this as discussed in here.

    table.setRowFactory(
        new Callback<TableView<Person>, TableRow<Person>>() {
            @Override
            public TableRow<Person> call(TableView<Person> tableView) {
                final TableRow<Person> row = new TableRow<>();
                final ContextMenu rowMenu = new ContextMenu();
                MenuItem editItem = new MenuItem("Edit");
                editItem.setOnAction(...);
                MenuItem removeItem = new MenuItem("Delete");
                removeItem.setOnAction(new EventHandler<ActionEvent>() {
    
                    @Override
                    public void handle(ActionEvent event) {
                        table.getItems().remove(row.getItem());
                    }
                });
                rowMenu.getItems().addAll(editItem, removeItem);
    
                // only display context menu for non-empty rows:
                row.contextMenuProperty().bind(
                  Bindings.when(row.emptyProperty())
                  .then(rowMenu)
                  .otherwise((ContextMenu)null));
                return row;
        }
    });
    
    0 讨论(0)
  • 2021-02-05 19:00

    try this..

    ContextMenu cm = new ContextMenu();
    MenuItem mi1 = new MenuItem("Menu 1");
    cm.getItems().add(mi1);
    MenuItem mi2 = new MenuItem("Menu 2");
    cm.getItems().add(mi2);
    
    table.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
    
        @Override
        public void handle(MouseEvent t) {
            if(t.getButton() == MouseButton.SECONDARY) {
                cm.show(table, t.getScreenX(), t.getScreenY());
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题