目前,我正在 FXML 中构建一个项目,并希望在 SceneBuilder 2.0 中使用自定义 RichTextFX Java 类。我知道这将涉及自定义控件的使用,但是我目前对实际完成实现所需的步骤感到困惑。
package view;
public class LeftTextArea extends TextArea {
private CodeArea leftCode = new CodeArea();
//CodeArea - defining the areas for coloured text:
private static final String[] KEYWORDS = new String[] {
"Given", "Then", "And", "But", "Feature", "Scenario", "When", "Background"
};
private static final String KEYWORD_PATTERNS = "\\b(" + String.join("|", KEYWORDS) + ")\\b";
private static final String SEMICOLON = "\\;";
private static final String STRING = "\"([^\"\\\\]|\\\\.)*\"";
private static final String BRACKET = "\\[|\\]";
private static final String PARENTHESIS = "\\(|\\)";
//CodeArea - Defining the pattern used for the Keywords using Regex commands:
//CodeArea - Compiling the pattern using the Java Regex Pattern class:
private static final Pattern PATTERN = Pattern.compile(
"(?<KEYWORD>" + KEYWORD_PATTERNS + ")"
+ "|(?<SEMICOLON>" + SEMICOLON + ")"
+ "|(?<STRING>" + STRING + ")"
+ "|(?<BRACKET>" + BRACKET + ")"
+ "|(?<PARENTHESIS>" + PARENTHESIS + ")"
);
public void start(Stage primaryStage) throws Exception {
leftCode.setParagraphGraphicFactory(LineNumberFactory.get(leftCode));
leftCode.richChanges().filter(ch -> !ch.getInserted().equals(ch.getRemoved())).subscribe(change -> {
leftCode.setStyleSpans(0, computeHighlighting(leftCode.getText()));
});
Scene scene = new Scene(leftCode, 500, 400);
scene.getStylesheets().add(LeftTextArea.class.getResource("GherkinView.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
private static StyleSpans<Collection<String>> computeHighlighting(String text) {
Matcher patternmatcher = PATTERN.matcher(text);
StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
int keywordend = 0;
while(patternmatcher.find()) {
String styleClass =
patternmatcher.group("KEYWORD") != null ? "keyword" :
patternmatcher.group("SEMICOLON") != null ? "semicolon" :
patternmatcher.group("STRING") != null ? "string" :
patternmatcher.group("BRACKET")!= null ? "bracket" :
patternmatcher.group("PARENTHESIS")!= null ? "parenthesis" :
null;
assert styleClass != null;
spansBuilder.add(Collections.emptyList(), patternmatcher.start() - keywordend);
spansBuilder.add(Collections.singleton(styleClass), patternmatcher.end() - patternmatcher.start());
keywordend = patternmatcher.end();
}
spansBuilder.add(Collections.emptyList(), text.length() - keywordend);
return spansBuilder.create();
}
}
我尝试将其导出为 JAR 文件并将其导入 SceneBuilder,但是,它不可编辑并且无法按预期运行。这就是它在最终产品JavaFX GUI上的外观。
任何帮助将不胜感激,我很乐意进一步澄清。
谢谢,
查兰迪普