抓取文本时,一个字符后面的JavaFX Textfield

时间:2017-05-31 19:38:16

标签: java

下面的代码由JavaFX文本字段中的类型键触发,始终位于一个字符后面。例如,如果用户键入k,则为searchBar.getText()打印的字符串等于""。如果用户输入另一个k,它将等于" k",依此类推。

   //this is triggered when a key is typed into search bar
        @FXML public void onKeyPressedOnSearch(){
            File[] fileCollection = model.getFileCollection();


            System.out.println(searchBar.getText());
            System.out.println(fileCollection[0].getName().substring(0, searchBar.getText().length()));
            List<String> list = new ArrayList<String>();
            ObservableList<String> tempObservableList = FXCollections.observableList(list);


        /*  for(int i = 0; i < fileCollection.length; i++){
                if(!(searchBar.getText().equals(fileCollection[i].getName().substring(0, searchBar.getText().length())))){
                    tempObservableList.remove(i);
                }
            }


            if(searchBar.getText() == null || searchBar.getText() == ""){
                songList.setItems(observableList);
            }else{
                songList.setItems(tempObservableList);
            } */
        }

1 个答案:

答案 0 :(得分:2)

我建议在ChangeListener添加TextField,以便您可以从那里获取任何更改,请考虑以下示例:

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class CharByCharGrabbing extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        // create simple root and add two text fields to it
        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        // just styling
        root.setBackground(new Background(new BackgroundFill(Color.MAGENTA, null,null)));

        TextField textField = new TextField();
        TextField textField1 = new TextField();

        root.getChildren().addAll(textField, textField1);

        Scene scene = new Scene(root, 300,200);
        stage.setScene(scene);
        stage.setTitle("Grabbing Char by Char");
        stage.show();

        // Now you can add a change listener to the text property of the text field
        // it will keep you updated with every single change (char by char)
        // either adding to or removing from the TextField
        textField.textProperty().addListener((observable, oldText, newText)->{ // lambda style
            textField1.setText(newText); // update me when any change happens
            // so you can grab the changes from here.
        });

    }

    public static void main(String[] args) {
        launch();
    }
}

<强>测试

Test