从表格视图处理按钮单击事件 [英] Handle Button click event from Table view

查看:58
本文介绍了从表格视图处理按钮单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两列,一列是 Status ,这是我单击的列,另一列是 Approved By ,应在Button动作事件后更新. 我尝试过setOnAction

I have two columns, one is Status which is the one that I click and the other is Approved By which should update after the Button action event. I was try setOnAction by

getTableView().getSelectionModel().getSelectedItem().setApprovedby("User");

但这是行不通的.

请帮助我在Button相同行操作事件后如何在批准人列中显示文本.如下图所示

Please help me how to display text into Approved By column after the Button same row action event. It look like as below

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

// Here is button cell code to setCellFactory for Status column

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

//这是该控制器的类代码

//Here is controller class code for that

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

        }

    }

}

//这里是构造函数代码

// And constructor code here

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

推荐答案

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

It's not a good idea to store Nodes in the item class in most cases. In this case it's not a good idea. You mix up the visual representation of the data with the data itself.

由于无法观察到approvedby属性,因此不会更新另一列中的单元格.对这个属性使用StringProperty可以忍受TableView可以观察到的属性更改:

The cell in the other column won't be updated, since the approvedby property is not observable. Use a StringProperty for this property to endure changes to the property can be observed by TableView:

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

    ...
}

工程控制器

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已被接受,前提是有人!= ""批准了它.可以使用例如而是一个布尔属性.

Note: in the code above I assume that a thamso is accepted iff someone != "" has approved it. It's possible to use e.g. a boolean property for this instead.

这篇关于从表格视图处理按钮单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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