简体   繁体   English

JavaFX:如何识别TableView中的当前行?

[英]JavaFX: how to recognise current row in TableView?

People Table - TableView Example 人员表-TableView示例

I've built a TableView in JavaFX as shown in the image (People Table) consisting of a list of names. 我已经在JavaFX中构建了一个TableView,如由名称列表组成的图像(People Table)所示。 How can I have the first and last name printed to console on the corresponding row every time the 'details' button is clicked? 每次单击“详细信息”按钮时,如何在相应的行上将名字和姓氏打印到控制台上?

(For reference my final goal and original unanswered question is for the details button to open a template scene and to populate it with data for that specific person). (作为参考,我的最终目标和原始未解决的问题是使用“详细信息”按钮来打开模板场景,并使用该特定人员的数据填充它)。

import javafx.application.Application;
import javafx.beans.property.*;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.*;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.util.Callback;

public class cutExample extends Application {
  public static void main(String[] args) { launch(args); }


  @Override public void start(final Stage stage) {
    stage.setTitle("People");

    // create a table.
    final TableView<Person> table = new TableView<>(
      FXCollections.observableArrayList(
        new Person("Jacob", "Smith"),
        new Person("Isabella", "Johnson"),
        new Person("Ethan", "Williams"),
        new Person("Emma", "Jones"),
        new Person("Michael", "Brown")
      )
    );

    // define the table columns.
    TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
    firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName"));
    TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
    lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName"));
    TableColumn<Person, Boolean> actionCol = new TableColumn<>("Action");
    actionCol.setSortable(false);


    // create a cell value factory with a details button for each row in the table.
    actionCol.setCellFactory(new Callback<TableColumn<Person, Boolean>, TableCell<Person, Boolean>>() {
      @Override public TableCell<Person, Boolean> call(TableColumn<Person, Boolean> personBooleanTableColumn) {
        return new AddPersonCell(stage, table);
      }
    });

    table.getColumns().setAll(firstNameCol, lastNameCol, actionCol);
    table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    stage.setScene(new Scene(table));
    stage.show();
  }

  /** A table cell containing a button for details on each person. */
  private class AddPersonCell extends TableCell<Person, Boolean> {
    // a button for a specific person's details
    final Button details       = new Button("Details");
    // pads and centers the button in the cell.
    final StackPane paddedButton = new StackPane();


    /**
     * AddPersonCell constructor
     * @param stage the stage in which the table is placed.
     * @param table the table to which a new person can be added.
     */
    AddPersonCell(final Stage stage, final TableView table) {
      paddedButton.setPadding(new Insets(3));
      paddedButton.getChildren().add(details);


    }

    /** places an details button in the row only if the row is not empty. */
    @Override protected void updateItem(Boolean item, boolean empty) {
      super.updateItem(item, empty);
      if (!empty) {
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
        setGraphic(paddedButton);
      } else {
        setGraphic(null);
      }
    }
  }


}

You can use the following snippet of code: 您可以使用以下代码段:

actionCol.setCellFactory(column -> new TableCell<Person, Void>() {

        @Override
        protected void updateItem(Void item, boolean empty) {
            super.updateItem(item, empty);
            if (!empty) {
                Button details = new Button("details");
                details.setOnAction(e ->{Person person= (Person)getTableRow().getItem(); System.out.println(person.getFirstName()+", "+person.getLastName());});
                setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                setGraphic(details);
            } else {
                setGraphic(null);
            }

        }

    });

Edit : to avoid casting you can use this: 编辑 :为避免强制转换,您可以使用以下命令:

 details.setOnAction(e ->{int  index = getTableRow().getIndex();
 Person person= getTableView().getItems().get(index);
System.out.println(person.getFirstName()+", "+person.getLastName());});

人somePersone = table.getSelectionModel()。getSelectedItem();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM