简体   繁体   English

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

[英]Handle Button click event from Table view

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. 我有两列,一列是“ 状态” ,这是我单击的列,另一列是“ 批准者” ,应在Button动作事件后更新。 I was try setOnAction by 我曾尝试通过setOnAction

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

But it doesn't work. 但这是行不通的。

Please help me how to display text into Approved By column after the Button same row action event. 请帮助我在Button相同行操作事件后如何在“ 批准者”列中显示文本。 It look like as below 如下图所示

在此处输入图片说明

// Here is button cell code to setCellFactory for Status column //这是setCellFactory的Status列的按钮单元格代码

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

It's not a good idea to store Node s in the item class in most cases. 在大多数情况下,将Node存储在item类中不是一个好主意。 In this case it's not a good idea. 在这种情况下,这不是一个好主意。 You mix up the visual representation of the data with the data itself. 您将数据的可视表示形式与数据本身混合在一起。

The cell in the other column won't be updated, since the approvedby property is not observable. 另一列中的单元格将不会被更新,因为无法观察approvedby属性。 Use a StringProperty for this property to endure changes to the property can be observed by TableView : 对这个属性使用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());

        ...
    }

    ...

}

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

Note: in the code above I assume that a thamso is accepted iff someone != "" has approved it. 注意:在上面的代码中,我假设如果有人批准了thamso就表示它thamso ""批准了它。 It's possible to use eg a boolean property for this instead. 可以为此使用例如布尔属性。

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

相关问题 如何处理表格视图中的按钮单击事件以创建超链接 - How to handle Button click event from Table view to create Hyperlink 表格行中的切换按钮未注册点击事件 - Switch button in table row not registering click event Android中XML对话框的按钮单击事件 - Button Click Event for Dialog from XML in Android 在自动完成文本视图中获取退格按钮单击动作事件 - Get back space button click action event in Autocomplete text view 在自定义列表视图中实施按钮单击 - Implementing button click from a custom list view 在Click事件上处理DownloadManager并从BroadcastReceiver启动系统下载应用程序 - Handle DownloadManager on click event and start system Downloads application from a BroadcastReceiver 我在一个按钮上有 LinearLayout。 有没有办法处理按钮点击事件? - I have LinearLayout over a button. Is there any way to handle underneath button click event? 如何在RecyclerView中处理点击事件 - How to handle click event in RecyclerView 在弹出窗口之外处理点击事件 - Handle click event outside popup 如何在javaFX中通过单击按钮的用户输入在表视图中填充数据 - How to populate data in table view with user input on button click in javaFX
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM