搜索并替换javafx TableView中的单个单词

时间:2018-06-04 10:13:14

标签: java javafx

以下代码用于搜索和替换TableView中的单词,但它正在替换所有单词,我不想要这样,所以我想要的是我只想替换一个单词不喜欢那个词会被所有地方所取代,我不想替换所有的功能来运行只想要单个词来运行。

public void onClickRep(ActionEvent event) {
    searchText.set(srep.getText());
    String replace;
    replace=rrep.getText();
    tc_source.setCellFactory(column ->  new TableCell<File, String>() {
        private final ChangeListener<String> listener = (o, oldValue, replace) -> {
              updateContents(getItem(), replace);
        };

        @Override
        protected void updateItem(String item, boolean empty) {

            super.updateItem(item, empty);
            searchText.removeListener(listener);

            if (item == null || empty) {
                setGraphic(null);
                setText(null);
            } else {
                updateContents(item, searchText.get());
                searchText.addListener(listener);
            }

        }

        private void updateContents(String item, String search) {
            if (search == null || search.isEmpty() || !item.toLowerCase().contains(search.toLowerCase())) {
                setText(item);
                setTextFill(javafx.scene.paint.Color.BLACK);
                setContentDisplay(ContentDisplay.TEXT_ONLY);
            } else {
                double rowHeight = this.getTableRow().getHeight();
                setGraphic(buildTextFlow(item, search));
                setHeight(rowHeight);
                setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            }
        }

        private TextFlow buildTextFlow(String text, String filter) {
            int filterLength = filter.length();
            if (filterLength == 0) {
                return new TextFlow(createNormalText(text));
            }                   Font font = Font.font("Italic", 12);

            java.awt.Color color= java.awt.Color.BLUE ;

            TextFlow t = new TextFlow();
            String lowerText = text.toLowerCase();
            filter = filter.toLowerCase();
            int index1 = 0;
            int matchIndex=0;
            while ((matchIndex = lowerText.indexOf(filter, index1)) != -1) {
                if (index1 != matchIndex) {
                    t.getChildren().add(createNormText(text.substring(index1, matchIndex)));
                }
                index1 = matchIndex + filterLength;
                t.getChildren().add(createReplace(text.substring(matchIndex, index1), replace));


            }
            if (index1 != text.length()) {
                t.getChildren().add(createNormText(text.substring(index1)));
            }
            return t;
        }
    });

}

public static Text createReplace(String text, String replace) {
    Text result = new Text(text);
    result.setText(replace);
    System.out.println(result);
    return result;
}

public static Text createNormText(String text) {
    Text result = new Text(text);

    return result;
}

0 个答案:

没有答案
相关问题