我已经使用JavaFX大约两周了,删除行时TextArea出现问题。我在TextArea上附加了以下信息,但是如何删除特定行?
如何删除包含Laura Smith 55.12的行,而将其他两个留在那里? 我有第一个角色,但是我不确定从那里去哪里。请帮忙。
for (String line : reservationBox.getText().split("\n")) {
if(line.contains(nameText.getText() + " " + priceText.getText())) {
char firstCharacter = nameText.getText().charAt(0); //get character of the first letter of the name
reservationBox.deleteText( ?? );
}
}
答案 0 :(得分:1)
deleteText(startIndex, endIndex)
删除文本。看看下面的代码:
public void start(Stage primaryStage) throws Exception {
int indexStart = 0; //initialize variables
int indexEnd = 0;
TextArea textArea = new TextArea();
textArea.setText("123\nhello\nabc\ntwentyone\n"); //initialize text in box
VBox vbox = new VBox(textArea);
Scene scene = new Scene(vbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
for(String line : textArea.getText().split("\n")){
if(line.contains("abc")) { //change this to whatever you need
indexStart = textArea.getText().indexOf(line.charAt(0));
indexEnd = indexStart + line.length()-1;
}
textArea.deleteText(indexStart, indexEnd); //Delete between indexes
}
}
public static void main(String[] args) {
Application.launch(args);
}
答案 1 :(得分:0)
在下面查看这个简单的应用程序,并将所有需要的内容都应用到您的代码中:
/**
*
* @author Momir Sarac
*/
public class DeleteSpecificLineFromTextArea extends Application {
@Override
public void start(Stage primaryStage) {
TextArea textArea = new TextArea();
Button button = new Button("Get it");
textArea.setText("Adam Smith 32\nJenny Curry 52\nTako Yoshimoto 56\n");
String nameText = "Jenny Curry 52";
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
for (String line : textArea.getText().split("\n")) {
if (line.contains(nameText)) {
textArea.setText(textArea.getText().replace(line, ""));
}
}
textArea.setText(textArea.getText().replaceAll("[\\\\\\r\\\\\\n]+", "\n"));
}
});
StackPane root = new StackPane();
root.getChildren().addAll(textArea,button);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}