поиск слова по ключу ввод - PullRequest
0 голосов
/ 26 декабря 2018

У меня проблема с моим методом поиска.

С помощью этого метода я могу ввести слово в текстовое поле и отобразить слово в текстовой области.Тем не менее, это происходит только один раз, если я позволю ему работать.Мне нужно расширить его так, чтобы каждый раз, когда я нажимал «ввод», программа продолжала поиск в текстовой области.Как я могу это сделать?И, пожалуйста, дайте мне примеры кода.У меня осталось всего 2 дня для презентации.

Большое спасибо за помощь

textfield.setOnKeyPressed(new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.ENTER)  {
                String text = textarea.getText();

              Labeled errorText = null;
            if (textfield.getText() != null && !textfield.getText().isEmpty()) {
                    index = textarea.getText().indexOf(textfield.getText()); 
                    textarea.getText();

                    if (index == -1) {
                        errorText.setText("Search key Not in the text");
                    } else {
                      //  errorText.setText("Found");
                        textarea.selectRange(index, index + textfield.getLength());

                        }


                    }   

                }
            }

        });

1 Ответ

0 голосов
/ 26 декабря 2018

Существует перегруженная версия indexOf метода , позволяющая выполнять поиск, начиная с определенного индекса.Следите за индексом вашей последней находки и начинайте поиск с этой позиции:

@Override
public void start(Stage primaryStage) throws Exception {

    TextField textField = new TextField("foo");
    TextArea textarea = new TextArea();
    for (int i = 0; i < 10; i++) {
        textarea.appendText("foo\nbarfoobarfoofoo\n");
    }

    textField.setOnAction(evt -> {
        String searchText = textField.getText();
        if (searchText.isEmpty()) {
            return; // searching for empty text doesn't make sense
        }
        int index = textarea.getSelection().getEnd();

        // in case of the first search, start at the beginning
        // TODO: adjust condition/starting index according to needs
        if (textarea.getSelection().getLength() == 0) {
            index = 0;
        }

        // find next occurrence
        int newStartIndex = textarea.getText().indexOf(searchText, index);

        // mark occurrence
        if (newStartIndex >= 0) {
            textarea.selectRange(newStartIndex, newStartIndex + searchText.length());
        }
    });

    Scene scene = new Scene(new VBox(textField, textarea));
    primaryStage.setScene(scene);
    primaryStage.show();
}

Редактировать

Если вы не удовлетворены поиском элемента после выбора (или после курсора,если диапазон не выбран), вы можете сохранить данные конца последнего совпадения:

@Override
public void start(Stage primaryStage) throws Exception {

    TextField textField = new TextField("foo");
    TextArea textarea = new TextArea();
    for (int i = 0; i < 10; i++) {
        textarea.appendText("foo\nbarfoobarfoofoo\n");
    }

    class SearchHandler implements EventHandler<ActionEvent> {
        int index = 0;

        @Override
        public void handle(ActionEvent event) {
            String searchText = textField.getText();
            String fullText = textarea.getText();

            if (index + searchText.length() > fullText.length()) {
                // no more matches possible
                // TODO: notify user
                return;
            }
            // find next occurrence
            int newStartIndex = textarea.getText().indexOf(searchText, index);

            // mark occurrence
            if (newStartIndex >= 0) {
                index = newStartIndex + searchText.length();
                textarea.selectRange(newStartIndex, index);
            } else {
                index = fullText.length();
                // TODO: notify user
            }
        }

    }

    SearchHandler handler = new SearchHandler();
    textField.setOnAction(handler);
    // reset index to search from start when changing the text of the TextField
    textField.textProperty().addListener((o, oldValue, newValue) -> handler.index = 0);

    Scene scene = new Scene(new VBox(textField, textarea));
    primaryStage.setScene(scene);
    primaryStage.show();
}
...