Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to dynamically change css chart style?

BanjoMonMar 13 2014 — edited Mar 13 2014

What is the correct method to dynamically override the JavaFx 2.2 chart style in code? I've modified the tutorial sample below with and without loading of the css file. So far I am unable to override the style from the code. My goal is to dynamically set the width of each line. We're using Java 7_51 (64-bit) with Eclipse on Windows 7. The CSS generated in the code below works when it is in the file. There has to be a better way than write out a new file and read it back in, right?

      String title = "Chart Title";

      stage.setTitle("Stage Title");

      final LogAxis xAxis = new NumberAxis();

      final NumberAxis yAxis = new NumberAxis();

      final LineChart<Number, Number> chart = new LineChart<>(xAxis, yAxis);

      chart.setTitle(title);

      chart.setLegendVisible(false);

      chart.setCreateSymbols(false);

      xAxis.setLabel("x-axis");

      yAxis.setLabel("y-axis");

      // each bar is a line from x,0 to x,y

      int width = 24; // pixels

      for (int i = 0; i < ydata.length; i++)

      {

         String css = "";

         // TODO: dynamically calculate unique width for each "bar"

         final XYChart.Series data = new XYChart.Series();

         data.setName("Series" + (i + 1));

         data.getData().add(new XYChart.Data(xdata[i], 0.0f));

         data.getData().add(new XYChart.Data(xdata[i], ydata[i]));

         chart.getData().add(data);

         // Dynamically set style instead of reading from file

         // Assign each "bar" data series a color and line width

         css += ".chart-series-line{ -fx-stroke: red; -fx-stroke-width: ";

         css += width;

         css += "px; }\n";

         data.getNode().setStyle(css);

         System.out.println("node style: " + data.getNode().getStyle());

         System.out.println("node style class: " + data.getNode().getStyleClass());

         width *= 3; // TODO: replace this with dynamic calculation of width

      } // end for

      final Scene scene = new Scene(chart, 800, 600);

      scene.getStylesheets().add("Chart.css");

      System.out.println("Scene stylesheet: " + scene.getStylesheets());

      System.out.println("chart style: " + chart.getStyle());

      System.out.println("chart style class: " + chart.getStyleClass());

      System.out.println("chart style sheet: " + chart.getStylesheets());

      stage.setScene(scene);

      stage.show();

This post has been answered by David Grieve-Oracle on Mar 13 2014
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 10 2014
Added on Mar 13 2014
4 comments
4,062 views