简体   繁体   中英

Setting LineChart symbol via code without css in JavaFX

This question is based on this and this .

The user can pick a custom color, after that I need to display the line chart in this color. The lines do work as described in the second link:

String rgb = String.format("%d, %d, %d",
        (int) (user.getColor().getRed() * 255),
        (int) (user.getColor().getGreen() * 255),
        (int) (user.getColor().getBlue() * 255));
series.nodeProperty().get().setStyle("-fx-stroke: rgba(" + rgb + ", 1);");

I'm not able to change the symbols of the users chart. With css you would do this:

.default-color0.chart-line-symbol { -fx-background-color: #e9967a, white; }
.default-color1.chart-line-symbol { -fx-background-color: #f0e68c, white; }
.default-color2.chart-line-symbol { -fx-background-color: #dda0dd, white; }

I can't do this, because the user can choose any color possible. Is there a workaround?


I tried this, but this throws a NullPointerException :

chart.lookup(".default-color0.chart-line-symbol")
     .setStyle("-fx-background-color: rgba(" + rgb + ", 1), white;");

Adding a Platform.runLater(() -> chart.lo....) gets rid of the NullPointerException (I don't understand why) but only turns some points in the correct color, and never the legend.

Define a series of "looked-up colors", which you can then change programmatically.

In the external CSS file, set these to some default value, and define your background colors depending on them:

.line-chart {
    symbol-color0: #e9967a ;
    symbol-color1: #f0e68c ;
    symbol-color2: #dda0dd ;
    /* ... */
}

.default-color0.chart-line-symbol { -fx-background-color: symbol-color0, white; }
.default-color1.chart-line-symbol { -fx-background-color: symbol-color1, white; }
.default-color2.chart-line-symbol { -fx-background-color: symbol-color2, white; }

Then in your Java code you can redefine those to arbitrary colors:

Color[] colors = getUserDefinedColors();

StringBuilder style = new StringBuilder();
for (int i = 0 ; i < colors.length ; i++) {
    style.append("symbol-color")
         .append(i)
         .append(": ")
         .append(convertToWebString(colors[i]))
         .append("; ");
}
myLineChart.setStyle(style.toString());

with something like

private String convertToWebString(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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM