下面的这段代码由在 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);
} */
}
最佳答案
我建议向 TextField
添加一个 ChangeListener
,这样您就可以从那里获取任何更改,请考虑以下示例:
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();
}
}
测试
关于抓取文本时 JavaFX Textfield 位于一个字符后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44293376/