有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java文本区域javaFx颜色

我正在尝试开发一个看起来像终端控制台的应用程序,我正在使用一个文本区,我的愿望是有一个黑色背景和绿色文本

我想在不使用任何ccs模板的情况下实现这一点

我知道我的问题在这里看起来像是重复的:

javafx textarea background color not css

或者

JavaFX CSS styling of TextArea does not work

但在阅读了这些内容并尝试了它们的建议后,我发现没有运气解决我的问题

到目前为止我尝试的内容(未成功):

在FXML中:

<TextArea 
    fx:id="terminalTextArea"
    layoutX="14.0"
    layoutY="85.0"
    prefHeight="64.0"
    prefWidth="402.0"
    style="-fx-font-family: Consolas; -fx-highlight-fill: #00ff00; -fx-highlight-text-fill: #000000; -fx-text-fill: #00ff00; -fx-background-color:#000000;"
    text="Terminal"
    AnchorPane.leftAnchor="10.0"
    AnchorPane.rightAnchor="10.0">
    <font>
        <Font name="System Bold" size="14.0" />
    </font>
</TextArea>

在源代码中:

@Override
public void initialize(URL url, ResourceBundle rb) {
    System.out.println("init here");
    terminalTextArea.setStyle("-fx-text-fill: black;");
}

我唯一得到的是一种有边框的颜色,如下图所示:

enter image description here


共 (1) 个答案

  1. # 1 楼答案

    推荐的方法是使用外部CSS文件,如您链接的示例所示

    如果出于某种原因你不想那样做,试试看

    style="-fx-control-inner-background:#000000; -fx-font-family: Consolas; -fx-highlight-fill: #00ff00; -fx-highlight-text-fill: #000000; -fx-text-fill: #00ff00; "
    

    在FXML文件中,或等效地

    terminalTextArea.setStyle("-fx-control-inner-background:#000000; -fx-font-family: Consolas; -fx-highlight-fill: #00ff00; -fx-highlight-text-fill: #000000; -fx-text-fill: #00ff00; ");
    

    在控制器的initialize()方法中

    SSCCE:

    StyledTextArea。fxml:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.scene.layout.HBox?>
    <?import javafx.geometry.Insets?>
    <?import javafx.scene.control.TextArea?>
    <?import javafx.scene.text.Font?>
    
    <HBox xmlns:fx="http://javafx.com/fxml/1" >
        <padding>
            <Insets top="12" left="12" right="12" bottom="12"/>
        </padding>
        <TextArea 
            prefHeight="64.0"
            prefWidth="402.0"
            style="-fx-control-inner-background:#000000; -fx-font-family: Consolas; -fx-highlight-fill: #00ff00; -fx-highlight-text-fill: #000000; -fx-text-fill: #00ff00; "
            text="Terminal">
    
            <font>
                <Font name="System Bold" size="14.0" />
            </font>
        </TextArea>
    </HBox>
    

    还有一个测试班:

    import java.io.IOException;
    
    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    
    public class StyledTextArea extends Application {
    
        @Override
        public void start(Stage primaryStage) throws IOException {
            primaryStage.setScene(new Scene(
                FXMLLoader.load(getClass().getResource("StyledTextArea.fxml"))
            ));
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    enter image description here