JavaFX: TableView: get selected row cell values

时光毁灭记忆、已成空白 提交于 2021-02-04 08:34:05

问题


I'm working on a project where the TableView looks like this:

The datas are inside are a MySQL database, and I use a modell and an observableArrayList to get them.

I want to make an initialize method which read the whole selected Line and save it into the TextFields (like Name-Name, Address - Address etc). I tried with this, and now I can Select the Whole Line data, but can't split it into Strings to set the TextField texts:

ListViewerModell details = (ListViewerModell) table.getSelectionModel().getSelectedItem();

//Checking if any row selected
if (details != null) {
//??? - split
editName.setText("*Name*");
editAddress.setText("*Address*");
}

Tried with the modell getName(), getAdress() methods but I got NullPointerException and TablePos methods.


回答1:


// create table
TableView<Person> table = new TableView<Person>();

// create columns
TableColumn<Person, String> nameCol = new TableColumn<Person, String>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory("name"));

TableColumn<Person, Address> addressCol = new TableColumn<Person, String>("Address");
addressCol.setCellValueFactory(new PropertyValueFactory("address"));

// add columns 
table.getColumns().setAll(nameCol, addressCol);

// get data from db, return object List<Person> from DB 
ObservableList<Person> persons = getPersonsFromDB();
table.setItems(persons);

tableView.setOnMouseClicked((MouseEvent event) -> {
    if (event.getClickCount() > 1) {
        onEdit();
    }
});

public void onEdit() {
    // check the table's selected item and get selected item
    if (table.getSelectionModel().getSelectedItem() != null) {
        Person selectedPerson = table.getSelectionModel().getSelectedItem();
        nameTextField.setText(selectedPerson.getName());
        addressTextField.setText(selectedPerson.getAddress());
    }
}



回答2:


One way could be extracting the value of the columns of the selected row, like so :

   Object selectedItems = table.getSelectionModel().getSelectedItems().get(0);
   String first_Column = selectedItems.toString().split(",")[0].substring(1);
   System.out.println(first_Column);


来源:https://stackoverflow.com/questions/44097537/javafx-tableview-get-selected-row-cell-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!