JavaFX:添加Click Listener以识别在TableView

时间:2018-05-27 10:04:52

标签: java javafx tableview

我正在尝试添加一个Click Listener / MouseEvent,它可以识别我的TableView中的哪个单元格被单击。我使用字符串填充我的TableView列。目前我寻找的所有解决方案都获得了TableView的整行,但我希望能够只选择一个单元格并对该数据执行某些操作。我还需要获取单击的单元格的行和列,以便我可以将其映射到我的本地数据arraylist。总结如下: (1)可以识别单击了哪个单元格的监听器 (2)获取点击单元格的行和列

这是我目前使用TableView的类的控制器:

public class BookingsUIController {

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private MenuButton monthMenuButton;

    @FXML
    private Button updateTableButton;

    @FXML
    private MenuButton dateMenuButton;

    @FXML
    private Button submitBookingsButton;

    @FXML
    private TableView<Object> tableView;

    private int currentMonth;
    private int currentDate;

    @FXML
    void updateTableButtonClicked(ActionEvent event) {
        updateTableButton.setDisable(true);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, currentMonth);
        calendar.set(Calendar.DATE, currentDate);

        boolean dateChanged = Runner.changeDate(calendar);

        if(dateChanged) {
            //UPDATECELLS

            try {
                Main.showLoadingAlertLayout();
                //SHOW ALERT LOADING DIALOG FOR 2 SECs
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Main.dismissLoadingAlertLayout();
            Runner.updateCellsWithAvailability();

            populateTable();
        }
        else {
            //SHOW FAIL DIALOG
        }

        updateTableButton.setDisable(false);
    }

    @FXML
    void submitBookingsClicked(ActionEvent event) {

    }

    @FXML
    void initialize() {
        assert monthMenuButton != null : "fx:id=\"monthMenuButton\" was not injected: check your FXML file 'BookingsUIFXML.fxml'.";
        assert updateTableButton != null : "fx:id=\"updateTableButton\" was not injected: check your FXML file 'BookingsUIFXML.fxml'.";
        assert dateMenuButton != null : "fx:id=\"dateMenuButton\" was not injected: check your FXML file 'BookingsUIFXML.fxml'.";
        assert submitBookingsButton != null : "fx:id=\"submitBookingsButton\" was not injected: check your FXML file 'BookingsUIFXML.fxml'.";

        Calendar cal = Calendar.getInstance();
        currentMonth = cal.get(Calendar.MONTH);
        currentDate = cal.get(Calendar.DATE);
        populateMenus();
        initTable();
        populateTable();
    }

    void populateMenus() {
        String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        for(int k = 0; k < months.length; k++) {
            MenuItem item = new MenuItem(months[k]);
            item.setId(k+"");
            item.setOnAction(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent event) {
                    monthMenuButton.setText(item.getText());
                    currentMonth = Integer.parseInt(item.getId());

                }
            });
            monthMenuButton.getItems().add(item);
        }

        for(int i = 1; i <= 31; i++) {
            MenuItem item = new MenuItem(i + "");
            item.setId(i + "");
            item.setOnAction(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent event) {
                    dateMenuButton.setText(item.getText());
                    currentDate = Integer.parseInt(item.getId());
                }
            });
            dateMenuButton.getItems().add(item);
        }


    }

    void initTable() {

        tableView.skinProperty().addListener((obs, oldSkin, newSkin) -> {
            final TableHeaderRow header = (TableHeaderRow) tableView.lookup("TableHeaderRow");
            header.reorderingProperty().addListener((o, oldVal, newVal) -> header.setReordering(false));
        });

        tableView.setOnMouseReleased(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
//              // TODO Auto-generated method stub
//              
//              if(event.getButton().equals(MouseButton.PRIMARY)) {
//                  
//                  tableView.getSelectionModel().;
//                  TableCell<Object, String> cell = (TableCell<Object, String>)event.getSource();
//                  System.out.println("CLICKED: " + cell.getItem());
//              }

            }
        });



        TableColumn<Object, String> roomsCol = new TableColumn<Object, String>("");
//      roomsCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Object,String>, ObservableValue<String>>() {
//
//          @Override
//          public ObservableValue<String> call(CellDataFeatures<Object, String> param) {
//              // TODO Auto-generated method stub
//              return new ReadOnlyObjectWrapper<String>((String)param.getValue());
//          }
//      });

        roomsCol.setCellValueFactory(createCellValueCallback(0));
        roomsCol.setSortable(false);
        tableView.getColumns().add(roomsCol);


//      for(String room : Runner.rooms) {
//          tableView.getItems().add(room);
//      }
//      

        for(int i = 0; i < (Runner.times).size(); i++) {
            String time = Runner.times.get(i);
            final int index = i;
            TableColumn<Object, String> timesCol = new TableColumn<Object, String>(time);
            timesCol.setCellValueFactory(createCellValueCallback(i + 1));
            timesCol.setSortable(false);

            tableView.getColumns().add(timesCol);
//          tableView.getColumns().add(new TableColumn<ObservableList<Cell>, String>(time));
        }


    }

    void emptyTable() {
//      for(int i = 0; i < tableView.getItems().size(); i++) {
//          tableView.getItems().set(i, "");
//      }
        tableView.getItems().clear();
    }

    void populateTable() {
        emptyTable();
        for(ArrayList<Cell> cells : Runner.cellsByRows) {
            ObservableList<String> stringList = FXCollections.observableArrayList();
            stringList.add(cells.get(0).getRoom());
            for(int i = 0; i < cells.size(); i++) {
                String show = "";
                if(cells.get(i).isAvailable()) {
                    show = "OPEN";
                }
                else {
                    show = "X";
                }
                stringList.add(show);
            }
            tableView.getItems().add(stringList);

        }

        Runner.displayCells();

    }

    Callback<TableColumn.CellDataFeatures<Object,String>, ObservableValue<String>> createCellValueCallback(int i){
        final int index  = i;
        return new Callback<TableColumn.CellDataFeatures<Object,String>, ObservableValue<String>>() {

            @Override
            public ObservableValue<String> call(CellDataFeatures<Object, String> param) {
                // TODO Auto-generated method stub
                return new ReadOnlyObjectWrapper<String>(((ObservableList<String>)param.getValue()).get(index));
            }
        };
    }

}

感谢任何帮助。如果我能提供更多信息,请告诉我!

提前致谢

1 个答案:

答案 0 :(得分:1)

在每个列上设置一个单元工厂,用于创建具有适当侦听器的单元格:

    for(int i = 0; i < (Runner.times).size(); i++) {
        String time = Runner.times.get(i);
        final int index = i;
        TableColumn<Object, String> timesCol = new TableColumn<Object, String>(time);
        timesCol.setCellValueFactory(createCellValueCallback(i + 1));

        timesCol.setCellFactory(tc -> {
            TableCell<Object, String> cell = new TableCell<Object, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    setText(item);
                }
            };

            cell.setOnMouseClicked(event -> {
                if (! cell.isEmpty()) {
                    System.out.println("Click on column "+index+", row "+cell.getIndex());
                }
            });
            return cell ;
        });

        timesCol.setSortable(false);

        tableView.getColumns().add(timesCol);
    }