Created
March 5, 2013 22:59
-
-
Save jewelsea/5095145 to your computer and use it in GitHub Desktop.
Set a custom color sequence for a JavaFX pie chart.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javafx.application.Application; | |
import javafx.collections.*; | |
import javafx.scene.Scene; | |
import javafx.stage.Stage; | |
import javafx.scene.chart.*; | |
public class PieChartWithCustomColors extends Application { | |
@Override public void start(Stage stage) { | |
ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList( | |
new PieChart.Data("Grapefruit", 13), | |
new PieChart.Data("Oranges", 25), | |
new PieChart.Data("Plums", 10), | |
new PieChart.Data("Pears", 22), | |
new PieChart.Data("Apples", 30) | |
); | |
final PieChart chart = new PieChart(pieChartData); | |
chart.setLegendVisible(false); | |
stage.setScene(new Scene(chart)); | |
stage.show(); | |
applyCustomColorSequence( | |
pieChartData, | |
"aqua", | |
"bisque", | |
"chocolate", | |
"coral", | |
"crimson" | |
); | |
} | |
private void applyCustomColorSequence(ObservableList<PieChart.Data> pieChartData, String... pieColors) { | |
int i = 0; | |
for (PieChart.Data data : pieChartData) { | |
data.getNode().setStyle("-fx-pie-color: " + pieColors[i % pieColors.length] + ";"); | |
i++; | |
} | |
} | |
public static void main(String[] args) { launch(args); } | |
} |
Just remove applyCustomColorSequence( pieChartData, "aqua", "bisque", "chocolate", "coral", "crimson" );
and add this lines:
Scene scene = new Scene(chart);
scene.getStylesheets().add("/css/pie-chart-custom-colors.css");
stage.setScene(scene);
Now create a new .css
file and add this code:
.default-color0.chart-pie { -fx-pie-color: #ffd700; }
.default-color1.chart-pie { -fx-pie-color: #ffa500; }
.default-color2.chart-pie { -fx-pie-color: #860061; }
.default-color3.chart-pie { -fx-pie-color: #adff2f; }
.default-color4.chart-pie { -fx-pie-color: #ff5700; }
This way you will change the color of each element also you can use color names like this:
.default-color0.chart-pie { -fx-pie-color: blue; }
.default-color1.chart-pie { -fx-pie-color: red; }
.default-color2.chart-pie { -fx-pie-color: green; }
.default-color3.chart-pie { -fx-pie-color: yellow; }
.default-color4.chart-pie { -fx-pie-color: pink; }
This method is a reference to the documentation How to styling chart with CSS
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you can use this after initializing scene :
try
{
scene.getStylesheets().add("chart.css");
}
catch (Exception ex)
{
System.err.println("Cannot acquire stylesheet: " + ex.toString());
}
then :
use your style chart like this :
.data0.chart-pie
{
-fx-pie-color: #505FA3;
}
.data1.chart-pie{
-fx-pie-color: #9999ff;
}