将自定义JavaFX控件添加到Scenebuilder

时间:2017-04-04 00:36:49

标签: java javafx custom-controls scenebuilder richtextfx

目前,我正在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的外观。

任何帮助都会受到赞赏,我非常乐意进一步澄清。

谢谢,

Charandeep

0 个答案:

没有答案