JavaFX:TableView行选择

时间:2015-09-04 03:05:02

标签: java javafx tableview

我是第一次开发java / Javafx项目,我有TableView 多列(名称,名字,年龄......)来展示我的数据和我需要用户能够选择单行给予我每次所有信息关于此人(其他列),即使他点击在另一个专栏但我无法找到正确的方法。 当我选择一行时,我的代码每次都会给出我点击的单元格的值,但是我需要其他信息来搜索我的SQLite数据库并对其进行处理(删除/编辑此人..)

以下是我使用的代码:

...//rest of code

@Override
public void initialize(URL location, ResourceBundle resources) {

private TableView<Student> tbl_elev=new TableView<Student>();

...

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

... //rest of code

我在等你的建议和想法,我不介意你提出另一种方法,因为这可能是不兼容的(取自互联网)如果你需要代码的任何其他部分只是评论,我不会把它全部因为阅读时间太长..(对不起我的英语不好)

2 个答案:

答案 0 :(得分:3)

如果指定ChangeListener参数的类型为Student,则可以使用该对象中的实例方法:

这是Minimal, Complete, and Verifiable example

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class SSCCE extends Application {

    @Override
    public void start(Stage stage) {

        VBox root = new VBox();

        TableView<Student> studentsTable = new TableView<Student>();

        HBox studentBox = new HBox();
        Label studentHeader = new Label("Student: ");
        Label studentInfo = new Label("");
        studentBox.getChildren().addAll(studentHeader, studentInfo);

        root.getChildren().addAll(studentsTable, studentBox);

        // Prepare the columns
        TableColumn<Student, String> firstNameCol = new TableColumn<Student, String>(
                "First name");
        firstNameCol.setCellValueFactory(cellData -> cellData.getValue()
                .firstNameProperty());

        TableColumn<Student, String> lastNameCol = new TableColumn<Student, String>(
                "Last name");
        lastNameCol.setCellValueFactory(cellData -> cellData.getValue()
                .lastNameProperty());

        studentsTable.getSelectionModel().selectedItemProperty()
                .addListener(new ChangeListener<Student>() {

                    // Here's the key part. See how I specify that the
                    // parameters are of type student. Now you can use the
                    // instance methods from Student.
                    @Override
                    public void changed(
                            ObservableValue<? extends Student> observable,
                            Student oldValue, Student newValue ) {

                        studentInfo.setText(newValue.getFirstName() + " "
                                + newValue.getLastName());
                        // If you want to get the value of a selected student cell at
                        // anytime, even if it hasn't changed. Just do e.g.
                        // studentsTable.getSelectionModel().getSelectedItem().getFirstName()
                    }
                });

        studentsTable.getColumns().setAll(firstNameCol, lastNameCol);

        // Some mock Student objects
        Student student1 = new Student("Eric", "Smith");
        Student student2 = new Student("Brad", "Jones");
        Student student3 = new Student("Logan", "Thorpe");

        // Fill the table with students.
        studentsTable.getItems().addAll(student1, student2, student3);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

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

    // The student class. In this case an inner class to simplify the example. But generally you should never use inner classes.
    class Student {

        private StringProperty firstName;
        private StringProperty lastName;

        public Student(String firstName, String lastName) {
            this.firstName = new SimpleStringProperty(firstName);
            this.lastName = new SimpleStringProperty(lastName);
        }

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

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

        public StringProperty firstNameProperty() {
            return firstName;
        }

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

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

        public StringProperty lastNameProperty() {
            return lastName;
        }
    }

}

答案 1 :(得分:0)

经过多次失败的尝试后,感谢@Jonatan的回答,我在填写一些遗漏的单词之后的代码应该是这样的:

...//rest of code

@Override
public void initialize(URL location, ResourceBundle resources) {

private TableView<Student> tbl_elev=new TableView<Student>();

...

        tbl_elev.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Student>() {
              // Here's the key part. See how I specify that the
              // parameters are of type student. Now you can use the
              // instance methods from Student.
              @Override
              public void changed(ObservableValue<? extends Student> observable,Student oldValue, Student newValue){
                  if(newValue!=null){
                        System.out.println(newValue.getName() + " "+ newValue.getPrename()+" "+newValue.getNaiss());
                  }
              //you can add any other value from Student class via getter(getAdr,getMail,...)

              }
          });
}

... //rest of code

输出示例:

Jonatan stenbacka 2015-09-11

这些值已准备好用于获取数据库并在其中指定所需的行以进行处理。 希望有一天能帮助别人。 感谢...