使用外部 CSS 文件使用查找的颜色定义背景颜色(向下滚动链接到所有颜色样本的正下方):
.text-area {
text-area-background: blue ;
}
.text-area .content {
-fx-background-color: text-area-background ;
}
(这里text-area-background
本质上是您选择的任意变量名称。)
然后您可以以编程方式更新查找颜色的定义:
textArea.setStyle("text-area-background: green;");
这是一个SSCCE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class TextAreaColorSelection extends Application {
@Override
public void start(Stage primaryStage) {
ComboBox<Color> choices = new ComboBox<>();
choices.getItems().addAll(Color.ALICEBLUE, Color.AQUAMARINE, Color.CORNFLOWERBLUE,
Color.ANTIQUEWHITE, Color.BLANCHEDALMOND);
choices.setCellFactory(lv -> new ColorCell());
choices.setButtonCell(new ColorCell());
TextArea textArea = new TextArea();
choices.valueProperty().addListener((obs, oldColor, newColor) -> {
textArea.setStyle("text-area-background: "+ format(newColor) +";");
});
Scene scene = new Scene(new BorderPane(textArea, choices, null, null, null));
scene.getStylesheets().add("text-area-background.css");
primaryStage.setScene(scene);
primaryStage.show();
}
private String format(Color c) {
int r = (int) (255 * c.getRed());
int g = (int) (255 * c.getGreen());
int b = (int) (255 * c.getBlue());
return String.format("#%02x%02x%02x", r, g, b);
}
public static class ColorCell extends ListCell<Color> {
private final Rectangle rect = new Rectangle(80, 20);
public ColorCell() {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
@Override
public void updateItem(Color color, boolean empty) {
super.updateItem(color, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(rect);
rect.setFill(color);
}
}
}
public static void main(String[] args) {
launch(args);
}
}
使用 css 文件 text-area-background.css:
.text-area {
text-area-background: white ;
}
.text-area .content {
-fx-background-color: text-area-background ;
}