JavaFX:添加单击侦听器以标识在TableView中单击了哪个单元格 [英] JavaFX: Adding Click Listener to identify which cell was clicked in TableView

查看:64
本文介绍了JavaFX:添加单击侦听器以标识在TableView中单击了哪个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图添加一个Click Listener/MouseEvent,它可以识别TableView中的哪个单元格被单击.我用字符串填充TableView列.目前,我寻找的所有解决方案都可以获取TableView的整行内容,但是我希望能够仅选择一个单元格并对该数据进行某些处理.我还需要获取所单击的单元格的行和列,以便可以将其映射到我的本地数据arraylist.因此,总而言之: (1)可以识别单击哪个单元格的侦听器 (2)获取点击的单元格的行和列

I am trying to add a Click Listener/MouseEvent that can identify which cell in my TableView was clicked. I populate my TableView Columns with Strings. Currently all the solutions I have looked for get the whole row of the TableView, but I want to be able to select just one cell and do something with that data. I would also need to get the row and column of the clicked cell so that I can map it to my local data arraylist. So in summary: (1) Listener that can identify which cell was clicked (2) Get Row and Col of clicked cell

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

This is my Controller for the class with the TableView currently:

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));
            }
        };
    }

}

感谢任何帮助.请让我知道是否可以提供更多信息!

Any Help is Appreciated. Please let me know if I can provide any more info!

预先感谢

推荐答案

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

Set a cell factory on each column that creates cells with an appropriate listener:

    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);
    }

这篇关于JavaFX:添加单击侦听器以标识在TableView中单击了哪个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆