Skip to content

Instantly share code, notes, and snippets.

@jewelsea
Created December 2, 2011 10:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jewelsea/1422628 to your computer and use it in GitHub Desktop.
Save jewelsea/1422628 to your computer and use it in GitHub Desktop.
Creating a custom legend symbols for a Pie Chart in JavaFX 2.0
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Label;
import javafx.scene.effect.Glow;
import javafx.scene.effect.Reflection;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import java.util.Set;
public class PieChartCustomLegend extends Application {
@Override public void start(Stage stage) {
Scene scene = new Scene(new Group(), 500, 500);
stage.setTitle("Imported Fruits");
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.setTitle("Imported Fruits");
((Group) scene.getRoot()).getChildren().add(chart);
stage.setScene(scene);
stage.show();
Set<Node> items = chart.lookupAll("Label.chart-legend-item");
int i = 0;
// these colors came from caspian.css .default-color0..4.chart-pie
Color[] colors = { Color.web("#f9d900"), Color.web("#a9e200"), Color.web("#22bad9"), Color.web("#0181e2"), Color.web("#2f357f") };
for (Node item : items) {
Label label = (Label) item;
final Rectangle rectangle = new Rectangle(10, 10, colors[i]);
final Glow niceEffect = new Glow();
niceEffect.setInput(new Reflection());
rectangle.setEffect(niceEffect);
label.setGraphic(rectangle);
i++;
}
}
public static void main(String[] args) {
launch(args);
}
}
@jewelsea
Copy link
Author

jewelsea commented Dec 2, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment