On button click get selected row values to string in Javafx


Question

I need to select the row values and save them to strings. following is how i am populating all the data to the tabelview. Yet i don't know how to get the selected values on a button click. I know how to get the row ID and the on clicked value but don't know how to get the raw data.

Initializer class

public class controller implements Initializable {

    @FXML
    private TableView<TableRow> PasswordTabel;

    @FXML
    private TableColumn<TableRow, Object> ComName;

    @FXML
    private TableColumn<TableRow, Object> RepName;

    @FXML
    private TableColumn<TableRow, Object> RepDate;

    @FXML
    private TableColumn<TableRow, Object> RepPass;

    List<String> urls = new ArrayList<String>();

    public void initialize(URL location, ResourceBundle resources) {

        ComName.setCellValueFactory(new PropertyValueFactory<TableRow, Object>(
                "C_Name"));
        RepName.setCellValueFactory(new PropertyValueFactory<TableRow, Object>(
                "R_Name"));
        RepDate.setCellValueFactory(new PropertyValueFactory<TableRow, Object>(
                "R_Date"));
        RepPass.setCellValueFactory(new PropertyValueFactory<TableRow, Object>(
                "R_Pass"));

        ObservableList data = FXCollections.observableArrayList();
        try {
            File uxml = new File("Key.xml");
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(uxml);

            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("ReportDetails");
            for (int temp = 0; temp < nodeList.getLength(); temp++) {
                Node node = nodeList.item(temp);

                if (node.getNodeType() == Node.ELEMENT_NODE) {

                    Element student = (Element) node;

                    String C_nam = student.getAttribute("Cname");
                    String R_nam = student.getAttribute("Rname");
                    String R_dat = student.getAttribute("Rdate");
                    String R_pas = student.getAttribute("Rpw");
                    data.add(new Record(C_nam, R_nam, R_dat, R_pas));
                }
            }
            PasswordTabel.getItems().setAll(data);

        } catch (Exception e) {

        }

PasswordTabel.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observableValue, Object oldValue, Object newValue) {
                //Check whether item is selected and set value of selected item to Label
                if (PasswordTabel.getSelectionModel().getSelectedItem() != null) {
                    TableViewSelectionModel selectionModel = PasswordTabel.getSelectionModel();
                    ObservableList selectedCells = selectionModel.getSelectedCells();
                    TablePosition tablePosition = (TablePosition) selectedCells.get(0);
                    Object val = tablePosition.getTableColumn().getCellData(newValue);
                    System.out.println("Selected Value " + val);
                    System.out.println("Selected row " + newValue);
                }
            }
        });
    }
}

Record.class

public class Record {

    private final SimpleStringProperty C_Name;
    private final SimpleStringProperty R_Name;
    private final SimpleStringProperty R_Date;
    private final SimpleStringProperty R_Pass;

    Record(String name, String rname,String rdata, String rpass) {
        this.C_Name = new SimpleStringProperty(name);
        this.R_Name = new SimpleStringProperty(rname);
        this.R_Date = new SimpleStringProperty(rdata);
        this.R_Pass = new SimpleStringProperty(rpass);
    }

    public String getC_Name() {
        return this.C_Name.get();
    }

    public void setC_Name(String C_Name) {
        this.C_Name.set(C_Name);
    }

    public String getR_Name() {
        return this.R_Name.get();
    }

    public void setR_Name(String R_Na) {
        this.R_Name.set(R_Na);
    }
    public String getR_Date() {
        return this.R_Date.get();
    }

    public void setR_Date(String R_Da) {
        this.R_Date.set(R_Da);
    }

    public String getR_Pass() {
        return this.R_Pass.get();
    }

    public void setR_Pass(String R_Pa) {
        this.R_Pass.set(R_Pa);
    }

}

Tryed:

        PasswordTabel.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        PasswordTabel.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<Record>() {
            public void onChanged(ListChangeListener.Change<? extends Record> c) {

                for (Record p : c.getList()) {
                    System.out.println(p.getR_Pass());
                }

            }
        });

enter image description here

1
0
7/25/2014 2:33:23 PM

Accepted Answer

If the table is in Single selection mode, you can use

table.getSelectionModel().getSelectedItem()

If the table is in Multiple Selection mode, you can use

table.getSelectionModel().getSelectedItems()

EDIT - Adding an complete example with Listener

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
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.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

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

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

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

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

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

        table.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<Person>() {
            public void onChanged(ListChangeListener.Change<? extends Person> c) {

                for (Person p : c.getList()) {
                    System.out.println(p.getFirstName());
                }

            }
        });

        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);
        }
    }
} 
3
7/25/2014 2:17:07 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon