问题
I have a text area like below,
I need to highlight or select all the text "Highlight me". I don't find any methods to highlight the text in text area. Also I could not find any other API in JavaFX that highlights the occurrence of specific text or letter like JTextArea in Swing. Can any one suggest me on how to highlight String in the text area? Or is there any other API available apart from this text area in JavaFX?
My Code:
public class FXTextArea extends Application {
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(final Stage primaryStage) {
Group root = new Group();
final TextArea textArea = TextAreaBuilder.create().prefWidth(390)
.wrapText(true).build();
ScrollPane scrollPane = new ScrollPane();
scrollPane.getStyleClass().add("noborder-scroll-pane");
scrollPane.setContent(textArea);
scrollPane.setFitToWidth(true);
scrollPane.setPrefWidth(390);
scrollPane.setPrefHeight(180);
Button buttonLoad = new Button("Load");
buttonLoad.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
FileChooser fileChooser = new FileChooser();
// Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
"TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
// Show save file dialog
File file = fileChooser.showOpenDialog(primaryStage);
if (file != null) {
textArea.setText(readFile(file));
}
System.out.println(textArea.getText(0, 30));
textArea.selectRange(0, 30);
}
});
VBox vBox = VBoxBuilder.create().children(buttonLoad, scrollPane)
.build();
root.getChildren().add(vBox);
primaryStage.setScene(new Scene(root, 400, 300));
primaryStage.show();
}
private String readFile(File file) {
StringBuilder stringBuffer = new StringBuilder();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
String text;
while ((text = bufferedReader.readLine()) != null) {
stringBuffer.append(text);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(FXTextArea.class.getName()).log(Level.SEVERE,
null, ex);
} catch (IOException ex) {
Logger.getLogger(FXTextArea.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(FXTextArea.class.getName()).log(Level.SEVERE,
null, ex);
}
}
return stringBuffer.toString();
}
}
Expected output:
The lines should be highlight in any color as below. The "Highlight me" occurrence should be highlighted as below,
回答1:
You can take help from this. But the constraint is that you need to be on jdk8.
来源:https://stackoverflow.com/questions/22070261/highlight-text-in-javafx-textarea