2

I have the following tableColumn

TableColumn<TradePurchaseOrderManifest, Double> netweightCol = createColumn("netWeight", "Net Wgt",
                Double.class);

and the createColumn method

public static <T> TableColumn<TradePurchaseOrderManifest, T> createColumn(String name, String columHeading,
            Class<T> type) {
        TableColumn<TradePurchaseOrderManifest, T> column = new TableColumn<>(columHeading);
        column.setCellValueFactory(new PropertyValueFactory<>(name));
        column.setResizable(true);
        return column;
    }

This table have other columns as well which are of types ComboBoxTableCell etc. I wish to have a double click handler on this TextFieldTableCell AND only on this column. What I am able to achieve by now is to have a doubleClick handler on the tableview(row).

When I click on this cell, it converts to a TextFieldTableCell and then does not respond to double-clicks even if I am checking if it is an instance of TextFieldTableCell

        tableView.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                if (event.getClickCount() == 2) {
                    if (event.getTarget() instanceof TableCell<?,?>) {
                        System.out.println("dblCLick tableCell");
                    } else if (event.getTarget() instanceof TextFieldTableCell<?,?>) {
                        System.out.println("dblCLick textfield");
                    }
                }
            }
        });

Any suggestion on how to apply double click handler ONLY on this column and when it is a TextFieldTableCell.

Nitin Nanda
  • 805
  • 2
  • 11
  • 27
  • You can try to add click count to the Listener like this https://stackoverflow.com/a/19586049/12463079 – Dario Dec 03 '19 at 17:07
  • apparently I already have the click counter on the handler. It is not detecting if the mouseEvent target is the instance of TextFieldTableCell – Nitin Nanda Dec 03 '19 at 17:10
  • 1
    For columns, I like to use a context menu on the row that gives me options of what I can do to different columns. Just something to think about if no solution is found. – SedJ601 Dec 03 '19 at 17:14
  • That sounds correct. can you please suggest how can I add context menu to the rows and more important, how to use it to handle events on that column. – Nitin Nanda Dec 03 '19 at 17:34

1 Answers1

0

This is a workaround I use. I use ContextMenus to handle similar situations.

import java.util.Arrays;
import java.util.Optional;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

/**
 * Sedrick (SedJ601)
 * Uses code from https://gist.github.com/james-d/7758918, https://code.makery.ch/blog/javafx-dialogs-official/ and https://stackoverflow.com/questions/21009377/context-menu-on-a-row-of-tableview
 */
public class App extends Application {
    private TableView<Person> table = new TableView<Person>();
    private final ObservableList<Person> data =
        FXCollections.observableArrayList(
            new Person("Jacob", "Smith", "jacob.smith@example.com"),
            new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
            new Person("Ethan", "Williams", "ethan.williams@example.com"),
            new Person("Emma", "Jones", "emma.jones@example.com"),
            new Person("Michael", "Brown", "michael.brown@example.com")
        );

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(450);
        stage.setHeight(500);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        table.setEditable(true);

        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory<>("firstName"));

        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(
                new PropertyValueFactory<>("lastName"));

        TableColumn<Person, String> emailCol = new TableColumn<>("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
                new PropertyValueFactory<>("email"));

        table.setItems(data);
        table.getColumns().addAll(Arrays.asList(firstNameCol, lastNameCol, emailCol));

        table.setRowFactory((TableView<Person> tableView) -> {
            final TableRow<Person> row = new TableRow<>();

            final ContextMenu contextMenu = new ContextMenu();
            final MenuItem removeMenuItem = new MenuItem("Change last name");
            removeMenuItem.setOnAction((ActionEvent event) -> {
                Person tempPerson = table.getSelectionModel().getSelectedItem();
                int rowIndex = table.getSelectionModel().getSelectedIndex();

                TextInputDialog dialog = new TextInputDialog(tempPerson.getLastName());
                dialog.setTitle("Text Input Dialog");
                dialog.setHeaderText("Look, a Text Input Dialog");
                dialog.setContentText("Please enter a last name:");

                // Traditional way to get the response value.
                Optional<String> result = dialog.showAndWait();
                if (result.isPresent()){
                    tempPerson.setLastName(result.get());
                    tableView.getItems().set(rowIndex, tempPerson);
                }
            });
            contextMenu.getItems().add(removeMenuItem);
            // Set context menu on row, but use a binding to make it only show for non-empty rows:
            row.contextMenuProperty().bind(
                    Bindings.when(row.emptyProperty())
                            .then((ContextMenu)null)
                            .otherwise(contextMenu)
            );
            return row ;  
        });  

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(label, table);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Person(String fName, String lName, String email) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
            this.email = new SimpleStringProperty(email);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }

        public String getEmail() {
            return email.get();
        }

        public void setEmail(String fName) {
            email.set(fName);
        }
    }
} 
SedJ601
  • 12,173
  • 3
  • 41
  • 59