How can I select multiple cells in tableview with javafx only with the mouse?

I have an application with a tableview in javafx and I want to select more than one cell only with the mouse (something like the selection that exists in excel). I tried with setOnMouseDragged but I cant'n do something because the selection only returns the cell from which the selection started. Can someone help me?

For events of the mouse to be propagated to other than the node in which nodes the drag started, you must activate a 'full-drag-release press gesture' by calling startFullDrag (...) on the original node. (For more details, see the Javadocs MouseEvent and MouseDragEvent .) You can register for MouseDragEvents on cells of the table in order to receive and process these events.

Here's a simple example: the user interface is not supposed to be perfect, but it will give you the idea.

import java.util.Arrays;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;

public class DragSelectionTable extends Application {

    private TableView table = new TableView();
    private final ObservableList data =
        FXCollections.observableArrayList(
            new Person("Jacob", "Smith", "[email protected]"),
            new Person("Isabella", "Johnson", "[email protected]"),
            new Person("Ethan", "Williams", "[email protected]"),
            new Person("Emma", "Jones", "[email protected]"),
            new Person("Michael", "Brown", "[email protected]")
        );

    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 firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory("firstName"));

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

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

        final Callback, TableCell> cellFactory = new DragSelectionCellFactory();
        firstNameCol.setCellFactory(cellFactory);
        lastNameCol.setCellFactory(cellFactory);
        emailCol.setCellFactory(cellFactory);

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

        table.getSelectionModel().setCellSelectionEnabled(true);
        table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        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 DragSelectionCell extends TableCell {

        public DragSelectionCell() {
            setOnDragDetected(new EventHandler() {
                @Override
                public void handle(MouseEvent event) {
                    startFullDrag();
                    getTableColumn().getTableView().getSelectionModel().select(getIndex(), getTableColumn());
                }
            });
            setOnMouseDragEntered(new EventHandler() {

                @Override
                public void handle(MouseDragEvent event) {
                    getTableColumn().getTableView().getSelectionModel().select(getIndex(), getTableColumn());
                }

            });
        }
        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (empty) {
                setText(null);
            } else {
                setText(item);
            }
        }

    }

    public static class DragSelectionCellFactory implements Callback, TableCell> {

        @Override
        public TableCell call(final TableColumn col) {
            return new DragSelectionCell();
        }

    }

    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);
        }
    }

}

Tags: Java

Similar Questions

Maybe you are looking for

  • Mozilla think I'm under v6 - I am actually running v25. Why?

    Your site think that my version of FF is outdated and I use Windows7. I'm not. I am running FF on Mac OS 10.6.8 25.0 v (Netalyrz also I'm bf6 under Windows.Your convenience store also I am bf6 under Windows.) "About Firefox" watch v 25.0

  • Ref FPGA type-def lost connection when moving to another computer

    I have a VI that opens an FPGA VI reference and links the reference to the type definition. The VI works fine on a single computer (Win7; LV 2010, module FPGA 10.0.0). However, when I open the same VI on another computer (WinXP, LV 2010, module FPGA

  • error 641 and 80070641

    I think that my windows installer is damaged I looked for error codes and it is said to run fixit and I did. FixIt says it can't find steps and problems, I also used various suggestions online rInstaller windows install but when I try to rename msli.

  • XPS13 built in microphone not detected.

    On a Dell XPS 13 Ultrabook, running Windows 7 ultimate (downgraded from Windows 8). The system is not just see the microphones.  On the windows volume control options/recording devices, nothing comes up.  Even on Dell Audio / microphone and Skype mic

  • Windows and Nero reports missing atl100.dll 2015

    Is there some other way that restore Windows 7 Home Premium to fix programs report a Windows system file are missing. As with XP, you can put the installation disc in and repair. I programs telling me that "atl110.dll" is missing, I checked and it's