从表视图处理按钮单击事件

时间:2018-06-12 11:01:33

标签: java javafx javafx-8 javafx-2

我有两列,一个是状态,是我点击的那个,另一个是 Approved By ,它应该在Button动作事件后更新。 我是通过

尝试setOnAction
getTableView().getSelectionModel().getSelectedItem().setApprovedby("User");

但它不起作用。

请帮助我在Button同一行动作事件后如何在 Approved By 列中显示文本。它看起来如下所示

enter image description here

//这是 Status 列的setCellFactory的按钮单元格代码

public class Buttoncell implements Callback<TableColumn<thamso, Button>, TableCell<thamso, Button>> {

    @Override
    public TableCell<thamso, Button> call(TableColumn<thamso, Button> arg) {

        TableCell<thamso, Button> cell = new TableCell<thamso, Button>() {
        // TODO Auto-generated method stub

            protected void updateItem(Button item, boolean empty) {
                if (!empty) {
                    item.setOnAction(e -> {
                        getTableView().getSelectionModel().getSelectedItem().setApprovedby("User");

                        item.setText("Approved");;

                        item.getStyleClass().removeAll("addBobOk, focus");

                        item.getStyleClass().add("addBobOk");

                    });
                }
                setGraphic(item);
            }
        };
        return cell;
    }
}

//这是

的控制器类代码
public class Engineeringcontroller {

    @FXML
    private TextField searchField;
    @FXML
    private TableColumn<?, ?> partname;

    @FXML
    public TableView<thamso> infortable;
           // @FXML
    //TableView<thamso> infortable=new TableView<>();

    @FXML
    private TableColumn<?, ?> no;

    @FXML
    private TableColumn<?, ?> note;

    @FXML
    private TableColumn<?, ?> rev;

    @FXML
    private TableColumn<?, ?> quantity;

    @FXML
    private TableColumn<thamso, Hyperlink> link;

    @FXML
    private TableColumn<?, ?> qtyperset;

    @FXML
    private TableColumn<?, ?> weight;

    @FXML
    private TableColumn<?, ?> drawingname;

    @FXML
    private AnchorPane acr2;

    @FXML
    private AnchorPane acr;

    @FXML
    private TableColumn<?, ?> material;

    @FXML
    private TableColumn<?, ?> drawingno;

    @FXML
    private Button btnextract;
    @FXML
    private Button browse;
    @FXML
    private TableColumn<?, ?> model;

    @FXML
    private TextField txtlocation;

    @FXML
    private TableColumn<?, ?> projectid;

    @FXML
    private TableColumn<?, ?> spare;
    @FXML
    public TableColumn<thamso, String> approvedby;
    @FXML
    private TableColumn<?, ?> dateimport;
    @FXML
    private TableColumn<?, ?> importby;
    @FXML
    private TableColumn<?, ?> dateapproval;
    @FXML
    private TableColumn<thamso, Button> status;
    @FXML
    private ScrollPane scrollpane;
        //    private static String text ;
    // Declare more variable

    public static ObservableList<thamso> data = FXCollections.observableArrayList();
    String tenbanve;
    String masobanve;
    String suadoi;
    String masochetao;
    String kieubom;
    String tongsoluong;
    String dubi;
    String soluong1bo;
    String ten;
    String sothutu;
    String vatlieu;
    String kluong;
    String ghichu;
    String hyperlink;
    File selectedDirectory;

    public String userName = System.getProperty("user.name");
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    public String DATE = dateFormat.format(new Date());

    //    Timestamp datetime=new Timestamp(System.currentTimeMillis());

    @FXML
    public void initialize() {
        infortable.setEditable(true);
                // acl.getChildren().addAll(dataTable);

        scrollpane.setContent(infortable);
        scrollpane.setFitToWidth(true);
        scrollpane.setFitToHeight(true);
        scrollpane.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
        scrollpane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);

        //show initial tableview
        projectid.setCellValueFactory(new PropertyValueFactory<>("projectid"));
        model.setCellValueFactory(new PropertyValueFactory<>("model"));
        drawingname.setCellValueFactory(new PropertyValueFactory<>("drawingname"));
        partname.setCellValueFactory(new PropertyValueFactory<>("partname"));
        quantity.setCellValueFactory(new PropertyValueFactory<>("quantity"));
        spare.setCellValueFactory(new PropertyValueFactory<>("spare"));
        qtyperset.setCellValueFactory(new PropertyValueFactory<>("Qtyperset"));
        no.setCellValueFactory(new PropertyValueFactory<>("No"));
        material.setCellValueFactory(new PropertyValueFactory<>("material"));
        weight.setCellValueFactory(new PropertyValueFactory<>("weight"));
        note.setCellValueFactory(new PropertyValueFactory<>("note"));
        drawingno.setCellValueFactory(new PropertyValueFactory<>("drawing"));
        rev.setCellValueFactory(new PropertyValueFactory<>("rev"));
        link.setCellValueFactory(new PropertyValueFactory<>("hyperlink"));
        //link.setCellFactory(tc -> new Setlink<>());
        link.setCellFactory(new HyperlinkCell());
        importby.setCellValueFactory(new PropertyValueFactory<>("importby"));
        dateimport.setCellValueFactory(new PropertyValueFactory<>("dateimport"));

        approvedby.setCellValueFactory(new PropertyValueFactory<>("approvedby"));
        approvedby.setCellFactory(TextFieldTableCell.<thamso>forTableColumn());
        dateapproval.setCellValueFactory(new PropertyValueFactory<>("dateapproval"));

        status.setCellValueFactory(new PropertyValueFactory<>("statusaproval"));
        status.setCellFactory(new Buttoncell());

        // SEACRH TYPO INSIDE OF TABBLE VIEW . phương thức sẽ hoạt động đúng khi các field tring bảng dữ liệu có giá trị liên tục. không 1 vị trí nào ngắt quãng 
        FilteredList<thamso> filteredData = new FilteredList<>(data, e -> true);
        searchField.setOnKeyReleased(e -> {
            searchField.textProperty().addListener((observableValue, oldValue, newValue) -> {
                filteredData.setPredicate((Predicate<? super thamso>) user -> {
                    if (newValue == null || newValue.isEmpty()) {
                        return true;
                    }
                    String lowerCaseFilter = newValue.toLowerCase();
                    if (user.getProjectid().toLowerCase().contains(lowerCaseFilter)) {
                        return true;
                    } else if (user.getModel().toLowerCase().contains(lowerCaseFilter)) {
                        return true;
                    } else if (user.getDrawingname().toLowerCase().contains(lowerCaseFilter)) {
                        return true;
                    } else if (user.getPartname().toLowerCase().contains(lowerCaseFilter)) {
                        return true;
                    } else if (user.getMaterial().toLowerCase().contains(lowerCaseFilter)) {
                        return true;
                    } else if (user.getNote().toLowerCase().contains(lowerCaseFilter)) {
                        return true;
                    } else if (user.getDrawing().toLowerCase().contains(lowerCaseFilter)) {
                        return true;
                    } else if (user.getHyperlink().getText().toLowerCase().contains(lowerCaseFilter)) {
                        return true;
                    } else if (String.valueOf(user.getQuantity()).contains(newValue)) {
                        return true;
                    } else if (String.valueOf(user.getSpare()).contains(newValue)) {
                        return true;
                    } else if (String.valueOf(user.getQtyperset()).contains(newValue)) {
                        return true;
                    } else if (String.valueOf(user.getNo()).contains(newValue)) {
                        return true;
                    } else if (String.valueOf(user.getWeight()).contains(newValue)) {
                        return true;
                      //      }else if(user.getGio().contains(newValue)){
                        //              return true;
                        //      }else if(user.getNgay().contains(newValue)){
                        //          return true;
                        //     }else if(user.getManhanvien().contains(newValue)){
                        //         return true;

                    }
                    return false;
                });
            });
            SortedList<thamso> sortedData = new SortedList<>(filteredData);
            sortedData.comparatorProperty().bind(infortable.comparatorProperty());
            infortable.setItems(sortedData);

        });
    }

    public String checkstring(String input) {
        if (input != null && !input.isEmpty()) {
            return input.trim();
        } else {
            return null;
        }
    }

    public int checkInt(String input) {
        if (input != null && !input.isEmpty()) {
            return Integer.parseInt(input.replaceAll("\\s+", ""));
        } else {
            return 0;
        }
    }

    public float checkfloat(String input) {
        if (input != null && input.length() > 0) {
            try {
                return Float.parseFloat(input.replaceAll("\\s+", ""));
            } catch (Exception e) {
                return 0;
            }
        } else {
            return 0;
        }
    }

    public void browse() {
        //  FileInputStream fileIn = new FileInputStream(new File(txtlocation.getText()));
        final DirectoryChooser directoryChooser = new DirectoryChooser();
        Stage stage = (Stage) acr2.getScene().getWindow();

        selectedDirectory = directoryChooser.showDialog(stage);
        System.out.println(selectedDirectory);
        txtlocation.setText(selectedDirectory.getAbsolutePath());
    }

    public void extract() {
        if (selectedDirectory == null) {
            //No Directory selected
            System.out.println("no file founded");

        } else {
            data.clear();
            //  System.out.println("ten duong dan folder "+selectedDirectory.getAbsolutePath());      
            File[] listOfFiles = new File(txtlocation.getText()).listFiles();

            for (File file : listOfFiles) {
                if (file.isFile()) {

                    System.out.println("Ten file " + file.getName());
                    System.out.println("Ten duong dan file" + selectedDirectory + file.getName());
                    PDFManager pdfManager = new PDFManager();
                    pdfManager.setFilePath(file.getAbsolutePath());
                    System.out.println("DUONG DAN" + file.getAbsolutePath());
                      //   System.out.print(pdfManager.ToText());
                    // TODO Auto-generated method stub
                    String text = null;
                    try {
                        text = pdfManager.ToText();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // TODO Auto-generated catch block
                        Alert alert = new Alert(AlertType.ERROR);
                        alert.setTitle("LỖI ");
                        alert.setHeaderText("Lỗi text convertion IOException !");
                        // Create expandable Exception.
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        e.printStackTrace(pw);
                        String exceptionText = sw.toString();

                        Label label = new Label("The exception stacktrace was:");

                        TextArea textArea = new TextArea(exceptionText);
                        textArea.setEditable(false);
                        textArea.setWrapText(true);

                        textArea.setMaxWidth(Double.MAX_VALUE);
                        textArea.setMaxHeight(Double.MAX_VALUE);
                        GridPane.setVgrow(textArea, Priority.ALWAYS);
                        GridPane.setHgrow(textArea, Priority.ALWAYS);

                        GridPane expContent = new GridPane();
                        expContent.setMaxWidth(Double.MAX_VALUE);
                        expContent.add(label, 0, 0);
                        expContent.add(textArea, 0, 1);

                        // Set expandable Exception into the dialog pane.
                        alert.getDialogPane().setExpandableContent(expContent);

                        alert.showAndWait();
                    }
                    System.out.println(text);
                    int i13 = text.indexOf("@");
                    while (i13 >= 0) {
                        //tham so  ban ve
                        int i = text.indexOf("Tên chi tiết:") + 13;
                        int i2 = text.indexOf("Tiêu đề");
                        tenbanve = text.substring(i, i2);

                        int i3 = text.indexOf("Mã số bản vẽ: ") + 14;
                        int i4 = text.indexOf("SĐ:");
                        masobanve = text.substring(i3, i4);

                        int i5 = text.indexOf("SĐ: ") + 4;
                        int i6 = text.indexOf("Mã số chế tạo");
                        suadoi = text.substring(i5, i6);

                        int i7 = text.indexOf("Mã số chế tạo: ") + 15;
                        int i8 = text.indexOf("Kiểu bơm");
                        masochetao = text.substring(i7, i8);

                        int i9 = text.indexOf("Kiểu bơm") + 11;
                        int i10 = text.indexOf("@", i9);
                        kieubom = text.substring(i9, i10);
                        // System.out.println(i13);
                        //tham so bang ke
                        int i14 = text.indexOf("\\", i13);
                        int i15 = text.indexOf("\\", i14 + 1);

                        int i16 = text.indexOf("\\", i15 + 1);

                        int i17 = text.indexOf("\\", i16 + 1);
                        int i18 = text.indexOf("\\", i17 + 1);

                        int i19 = text.indexOf("\\", i18 + 1);
                        int i20 = text.indexOf("\\", i19 + 1);
                        // int i20=(text.indexOf("\\", i19+1)<text.length()) ?text.indexOf("\\", i19+1):text.length();

                        int i21 = text.indexOf("\\", i20 + 1);
                        // int i21=(text.indexOf("\\", i20+1)<text.length()) ?text.indexOf("\\", i20+1):text.length();

                        tongsoluong = text.substring(i13 + 1, i14);
                        dubi = text.substring(i14 + 1, i15);
                        soluong1bo = text.substring(i15 + 1, i16);
                        ten = text.substring(i16 + 1, i17);
                        sothutu = text.substring(i17 + 1, i18);
                        vatlieu = text.substring(i18 + 1, i19);
                        kluong = text.substring(i19 + 1, i20);
                        //   ghichu=text.substring(i20+1,i21);
                        ghichu = text.substring(i20 + 1, Math.min(i21, text.length()));

                        hyperlink = file.getAbsolutePath();

                        System.out.println("\n tong so luong" + tongsoluong);
                        System.out.println("dubi" + dubi);
                        System.out.println("slg1bo" + soluong1bo);
                        System.out.println("ten chi tiet" + ten);
                        System.out.println("sthutu" + sothutu);
                        System.out.println("vatlieu" + vatlieu);
                        System.out.println("khoi luong" + kluong);
                        System.out.println("Ghi chu" + ghichu);

                        System.out.println("\n" + tenbanve);
                        System.out.println("\n" + masobanve);
                        System.out.println("\n" + suadoi);
                        System.out.println("\n" + masochetao);
                        System.out.println("\n" + kieubom);

                        data.add(new thamso(
                                checkstring(masochetao),
                                checkstring(kieubom),
                                checkstring(tenbanve),
                                checkstring(ten),
                                checkInt(tongsoluong),
                                checkInt(dubi),
                                checkInt(soluong1bo),
                                checkInt(sothutu),
                                checkstring(vatlieu),
                                checkfloat(kluong),
                                checkstring(ghichu),
                                checkstring(masobanve),
                                checkInt(suadoi),
                                hyperlink,
                                userName,
                                DATE,
                                "",
                                "",
                                "pending approval"
                        ));

                        //set data
                        infortable.setItems(data);

                        i13 = text.indexOf("@", i13 + 1);

                    }
                } else {
                    Alert alert = new Alert(AlertType.ERROR);
                    alert.setTitle("LỖI");
                    alert.setHeaderText(null);
                    alert.setContentText("Không có Bảng kê trong bản vẽ " + tenbanve.toUpperCase() + "\n Hoặc bảng kê không đúng tiêu chuẩn ");
                    alert.showAndWait();
                }
            }

        }

    }

}

//这里的构造函数代码

public class thamso {

    private String projectid;
    private String model;
    private String drawingname;
    private String partname;
    private int quantity;
    private int spare;
    private int Qtyperset;
    private int No;
    private String material;
    private float weight;
    private String note;
    private String drawing;
    private int rev;
    private Hyperlink hyperlink;
    private String importby;
    private String dateimport;
    private String approvedby;
    private String dateapproval;
    private Button statusaproval;
   // public Button click;
   //this.click = new Button("Download");//
   //this.hyperlink = new Hyperlink(hyperlink);//

    public thamso(String projectid, String model, String drawingname, String partname, int quantity, int spare,
            int qtyperset, int no, String material, float weight, String note, String drawing, int rev,
            String hyperlink, String importby, String dateimport, String approvedby, String dateapproval,
            String statusaproval) {
        super();
        this.projectid = projectid;
        this.model = model;
        this.drawingname = drawingname;
        this.partname = partname;
        this.quantity = quantity;
        this.spare = spare;
        Qtyperset = qtyperset;
        No = no;
        this.material = material;
        this.weight = weight;
        this.note = note;
        this.drawing = drawing;
        this.rev = rev;
        this.hyperlink = new Hyperlink(hyperlink);
        this.importby = importby;
        this.dateimport = dateimport;
        this.approvedby = approvedby;
        this.dateapproval = dateapproval;
        this.statusaproval = new Button(statusaproval);
    }

    public String getProjectid() {
        return projectid;
    }

    public void setProjectid(String projectid) {
        this.projectid = projectid;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getDrawingname() {
        return drawingname;
    }

    public void setDrawingname(String drawingname) {
        this.drawingname = drawingname;
    }

    public String getPartname() {
        return partname;
    }

    public void setPartname(String partname) {
        this.partname = partname;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int getSpare() {
        return spare;
    }

    public void setSpare(int spare) {
        this.spare = spare;
    }

    public int getQtyperset() {
        return Qtyperset;
    }

    public void setQtyperset(int qtyperset) {
        Qtyperset = qtyperset;
    }

    public int getNo() {
        return No;
    }

    public void setNo(int no) {
        No = no;
    }

    public String getMaterial() {
        return material;
    }

    public void setMaterial(String material) {
        this.material = material;
    }

    public float getWeight() {
        return weight;
    }

    public void setWeight(float weight) {
        this.weight = weight;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getDrawing() {
        return drawing;
    }

    public void setDrawing(String drawing) {
        this.drawing = drawing;
    }

    public int getRev() {
        return rev;
    }

    public void setRev(int rev) {
        this.rev = rev;
    }

    public Hyperlink getHyperlink() {
        return hyperlink;
    }

    public void setHyperlink(Hyperlink hyperlink) {
        this.hyperlink = hyperlink;
    }

    public String getImportby() {
        return importby;
    }

    public void setImportby(String importby) {
        this.importby = importby;
    }

    public String getDateimport() {
        return dateimport;
    }

    public void setDateimport(String dateimport) {
        this.dateimport = dateimport;
    }

    public String getApprovedby() {
        return approvedby;
    }

    public void setApprovedby(String approvedby) {
        this.approvedby = approvedby;
    }

    public String getDateapproval() {
        return dateapproval;
    }

    public void setDateapproval(String dateapproval) {
        this.dateapproval = dateapproval;
    }

    public Button getStatusaproval() {
        return statusaproval;
    }

    public void setStatusaproval(Button statusaproval) {
        this.statusaproval = statusaproval;
    }
}

1 个答案:

答案 0 :(得分:0)

在大多数情况下,将Node存储在项目类中并不是一个好主意。在这种情况下,这不是一个好主意。您将数据的可视化表示与数据本身混合在一起。

另一列中的单元格无法更新,因为approvedby属性不可观察。对此属性使用StringProperty以确保TableView可以观察到对该属性的更改:

thamso

public class thamso {

    ...
    private StringProperty approvedby;
    //private Button statusaproval;
    ...

    public thamso(String projectid, String model, String drawingname, String partname, int quantity, int spare,
            int qtyperset, int no, String material, float weight, String note, String drawing, int rev,
            String hyperlink, String importby, String dateimport, String approvedby, String dateapproval) {
        ...

        this.approvedby = new SimpleStringProperty(approvedby);
        this.dateapproval = dateapproval;
    }


    public String getApprovedby() {
        return approvedby.get();
    }

    public void setApprovedby(String approvedby) {
        this.approvedby.set(approvedby);
    }

    public StringProperty approvedbyProperty() {
        return this.approvedby;
    }

    ...
}

Engineeringcontroller

public class Engineeringcontroller {

    ...

    @FXML
    public TableColumn<thamso, String> approvedby;

    ...

    @FXML
    private TableColumn<thamso, String> status;

    ...

    @FXML
    public void initialize() {
        ...

        approvedby.setCellValueFactory(new PropertyValueFactory<>("approvedby"));
        approvedby.setCellFactory(TextFieldTableCell.<thamso>forTableColumn());

        ...

        status.setCellValueFactory(new PropertyValueFactory<>("approvedby"));
        status.setCellFactory(new Buttoncell());

        ...
    }

    ...

}

扣式

public class Buttoncell implements Callback<TableColumn<thamso, String>, TableCell<thamso, String>> {

    @Override
    public TableCell<thamso, String> call(TableColumn<thamso, String> arg) {

        TableCell<thamso, String> cell = new TableCell<thamso, String>() {

            private final Button button;

            {
                button = new Button();
                button.setOnAction(evt -> {
                    thamso item = (thamso) getTableRow().getItem();
                    item.setApprovedby("User");:
                });
            }

            @Override
            protected void updateItem(String item, boolean empty) {
                if (empty) {
                    // remove button
                    setGraphic(null);
                } else {
                    // set up button based on item
                    button.getStyleClass().remove("addBobOk");
                    if (item != null && !item.isEmpty()) {
                        button.getStyleClass().add("addBobOk");
                        button.setText("Approved");
                    } else {
                        button.setText("pending approval");
                    }
                    setGraphic(button);
                }
            }
        };
        return cell;
    }
}

注意:在上面的代码中,我假设如果有人请接受thamso!= ""已批准。可以使用例如相反,它是一个布尔属性。