Reload and display blank JavaFX BarChart after launching the program - javafx

I'm working on a JavaFX program that can display different grocery items as a BarChart. My code structure uses an initial loading class, GroceryGrapher.java, a controller, GroceryGrapherController.java, and an .fxml file, GroceryGrapher.fxml.
I'm relatively new to JavaFX and I've tried different approaches to creating and displaying my BarChart. For the most part I've resolved issues and can load the chart with its data and components, but my issue is that the chart won't display / update after the program has started. The BarChart is part of an AnchorPane (which all comes under a StackPane) in my FXML file, and I've tried to update it after initialization since it starts out blank but it remains blank.
The BarChart is part of the AnchorPane, which also has a MenuBar. My goal was to be able to update different parts of the BarChart via the MenuBar. When I load the program, the MenuBar and empty BarChart are loaded:
This is how I initialize my BarChart and its data:
public class GroceryGrapherController implements Initializable {
#FXML
private AnchorPane anchorPane = new AnchorPane();
#FXML
private NumberAxis xAxis = new NumberAxis();
#FXML
private CategoryAxis yAxis = new CategoryAxis();
#FXML
private BarChart<Number, String> groceryBarChart;
#FXML
//private Stage stage;
Parent root;
#Override
public void initialize(URL location, ResourceBundle resources) {
groceryBarChart = new BarChart<Number, String>(xAxis, yAxis);
groceryBarChart.setTitle("Horizontal Grocery List");
xAxis.setLabel("Number");
xAxis.setTickLabelRotation(90);
yAxis.setLabel("Grocery Type");
// Populate BarChart
XYChart.Series<Number, String> series1 = new XYChart.Series<>();
series1.setName("Chocolates");
series1.getData().add(new XYChart.Data<Number, String>(25601.34, "Reese"));
series1.getData().add(new XYChart.Data<Number, String>(20148.82, "Cadbury"));
series1.getData().add(new XYChart.Data<Number, String>(10000, "Mars"));
series1.getData().add(new XYChart.Data<Number, String>(35407.15, "Snickers"));
series1.getData().add(new XYChart.Data<Number, String>(12000, "Lindt"));
XYChart.Series<Number, String> series2 = new XYChart.Series<>();
series2.setName("Vegetables");
series2.getData().add(new XYChart.Data<Number, String>(57401.85, "Cabbage"));
series2.getData().add(new XYChart.Data<Number, String>(41941.19, "Lettuce"));
series2.getData().add(new XYChart.Data<Number, String>(45263.37, "Tomato"));
series2.getData().add(new XYChart.Data<Number, String>(117320.16, "Eggplant"));
series2.getData().add(new XYChart.Data<Number, String>(14845.27, "Beetroot"));
XYChart.Series<Number, String> series3 = new XYChart.Series<>();
series3.setName("Drinks");
series3.getData().add(new XYChart.Data<Number, String>(45000.65, "Water"));
series3.getData().add(new XYChart.Data<Number, String>(44835.76, "Coke"));
series3.getData().add(new XYChart.Data<Number, String>(18722.18, "Sprite"));
series3.getData().add(new XYChart.Data<Number, String>(17557.31, "Mountain Dew"));
series3.getData().add(new XYChart.Data<Number, String>(92633.68, "Beer"));
// Need to do this because of a bug with CategoryAxis... manually set categories
yAxis.setCategories(FXCollections.observableArrayList("Reese", "Cadbury", "Mars", "Snickers", "Lindt", "Cabbage", "Lettuce",
"Tomato", "Eggplant", "Beetroot", "Water", "Coke", "Sprite", "Mountain Dew", "Beer"));
groceryBarChart.getData().addAll(series1, series2, series3);
}
Now, I have an item:
In my MenuBar to load the BarChart (since it initially appears empty), which utilizes the a method I created, loadGraph. I've tried different methods to get my updated BarChart to show up with no major success. My initial idea was to use setScene in the loadGraph method to set the scene to the BarChart, as shown in this example.
Stage stage = (Stage) anchorPane.getScene().getWindow();
stage.setScene(new Scene(groceryBarChart, 800, 600));
While that did work, it naturally replaced the scene to solely consist of the BarChart, removing my MenuBar and previous GUI:
I saw this question which had a similar issue (I think) but I wasn't really sure how to apply it to my program. I got this code:
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("GroceryGrapher.fxml"));
root = (Parent) fxmlLoader.load();
GroceryGrapherController ggController = fxmlLoader.getController();
} catch (Exception e) {
e.printStackTrace();
}
I copied over my initialization from the initialize method to a new method and tried calling it with ggController but it didn't change anything. I also tried creating a new method, updateData:
#FXML
private void updateData() {
Platform.runLater(() -> {
groceryBarChart.setTitle("Horizontal Grocery List");
});
}
I tried calling it with ggController in the loadGraph method but my BarChart still didn't change.
I know I'm doing something wrong, but I'm not very familiar with the BarChart class and JavaFX in too much depth, so I figured I would come here to ask for help. I need to update the existing BarChart in my GUI so that my data can load without replacing the entire scene, in order for the MenuBar to remain visible in the scene able to perform functions. How would I go about altering the BarChart component part of my AnchorPane, updating the data as necessary, without completely replacing the scene as I did previously?
Thank you very much and sorry if this question is bad or my coding practices are wrong. All feedback would be much appreciated!
EDIT
Just in case it might help, here is my FXML code for the BarChart.
<BarChart fx:id="groceryBarChart" layoutY="31.0" prefHeight="566.0" prefWidth="802.0">
<xAxis>
<CategoryAxis fx:id="yAxis" side="BOTTOM" />
</xAxis>
<yAxis>
<NumberAxis side="LEFT" fx:id="xAxis" />
</yAxis>
</BarChart>

Most of the problems seem to be resolved, so I'll comment on this part only:
Ohh, I see. I increased the height and it seems to be thicker, thank you for your comment, that's very interesting behavior from the library. So I shouldn't use the approach I'm using?
Well, it depends. There is no other way to treat each data series as a separate list of categories in BarChart (at least, I'm not aware of any), so if you want to have groups of categories, each group with its own color, you'll have to use the same method as in your example.
The alternatives are to write your own implementation of bar chart layoutPlotChildren() method which will show only one bar per category (the only one if there are no two data series that contain the same category), or to find another chart library with those features. Of couse, you can always choose to show your data in different format (one data series for each month).
If you plan to use your original method, you'll have to adjust vertical position of bars (to center them again), and you'll have to fix bar height problem too:
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.chart.*;
import java.net.URL;
import java.util.ResourceBundle;
public class GroceryGrapherController implements Initializable {
#FXML
private NumberAxis xAxis;
#FXML
private CategoryAxis yAxis;
#FXML
private BarChart<Number, String> groceryBarChart;
//the height of one bar in the chart (if it can fit category area); you can pick another value
private final double barHeight = 10;
#Override
public void initialize(URL location, ResourceBundle resources) {
groceryBarChart.setTitle("Horizontal Grocery List");
//there's only one bar per category, so remove the gap (don't edit this, it's used in calculations)
groceryBarChart.setBarGap(0);
//gap between categories; you can pick another value
groceryBarChart.setCategoryGap(5);
//there're some bugs with the chart layout not updating when this is enabled, so disable it
groceryBarChart.setAnimated(false);
xAxis.setLabel("Number");
xAxis.setTickLabelRotation(90);
yAxis.setLabel("Grocery Type");
//if category height changes (ex. when you resize the chart), bar positions and height need to be recalculated
yAxis.categorySpacingProperty().addListener((observable, oldValue, newValue) ->
recalculateBarPositionsAndHeight()
);
//your original data
// Populate BarChart
final XYChart.Series<Number, String> series1 = new XYChart.Series<>();
series1.setName("Chocolates");
series1.getData().addAll(
new XYChart.Data<>(25601.34, "Reese"),
new XYChart.Data<>(20148.82, "Cadbury"),
new XYChart.Data<>(10000, "Mars"),
new XYChart.Data<>(35407.15, "Snickers"),
new XYChart.Data<>(12000, "Lindt")
);
final XYChart.Series<Number, String> series2 = new XYChart.Series<>();
series2.setName("Vegetables");
series2.getData().addAll(
new XYChart.Data<>(57401.85, "Cabbage"),
new XYChart.Data<>(41941.19, "Lettuce"),
new XYChart.Data<>(45263.37, "Tomato"),
new XYChart.Data<>(117320.16, "Eggplant"),
new XYChart.Data<>(14845.27, "Beetroot")
);
final XYChart.Series<Number, String> series3 = new XYChart.Series<>();
series3.setName("Drinks");
series3.getData().addAll(
new XYChart.Data<>(45000.65, "Water"),
new XYChart.Data<>(44835.76, "Coke"),
new XYChart.Data<>(18722.18, "Sprite"),
new XYChart.Data<>(17557.31, "Mountain Dew"),
new XYChart.Data<>(92633.68, "Beer")
);
groceryBarChart.getData().addAll(series1, series2, series3);
}
private void recalculateBarPositionsAndHeight() {
final int seriesCount = groceryBarChart.getData().size();
final double categoryHeight = yAxis.getCategorySpacing() - groceryBarChart.getCategoryGap();
final double originalBarHeight = categoryHeight / seriesCount;
final double barTranslateY = originalBarHeight * (seriesCount - 1) / 2;
//find the (bar) node associated with each series data and adjust its size and position
groceryBarChart.getData().forEach(numberStringSeries ->
numberStringSeries.getData().forEach(numberStringData -> {
Node node = numberStringData.getNode();
//calculate the vertical scaling of the node, so that its height matches "barHeight"
//or maximum height available if it's too big
double scaleY = Math.min(barHeight, categoryHeight) / originalBarHeight;
node.setScaleY(scaleY);
//translate the node vertically to center it around the category label
node.setTranslateY(barTranslateY);
})
);
}
}
I chose fixed bar height, but you don't need to (in which case you'll have to edit recalculateBarPositionsAndHeight method to use originalBarHeight).

Related

JavaFX LineChart Mouse Hover Values [duplicate]

I am in the process of creating a line chart in JavaFX. All is good currently and it successfully creates the chart with the data I need from a database stored procedure. Anyway what I require if possible is for every data point on the LineChart to have a mouse hover event on it which states the value behind the specific point, for example £150,000. I have seen examples of this been done on PieCharts where it shows the % value on hover but I cannot find examples anywhere for LineCharts, can this even be done?
Can anyone point me in the right direction if possible?
Code so far:
private static final String MINIMIZED = "MINIMIZED";
private static final String MAXIMIZED = "MAXIMIZED";
private static String chartState = MINIMIZED;
// 12 Month Sales Chart
XYChart.Series<String, Number> series = new XYChart.Series<>();
XYChart.Series<String, Number> series2 = new XYChart.Series<>();
public void getDeltaData() {
try {
Connection con = DriverManager.getConnection(connectionUrl);
//Get all records from table
String SQL = "";
Statement stmt = con.createStatement();
//Create the result set from query execution.
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
series.getData().add(new XYChart.Data<String, Number>(rs.getString(1),
Double.parseDouble(rs.getString(7))));
series2.getData().add(new XYChart.Data<String, Number>(rs.getString(1),
Double.parseDouble(rs.getString(8))));
}
rs.close();
stmt.close();
} catch (Exception e) {
}
yearChart = createChart();
}
protected LineChart<String, Number> createChart() {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
// setup chart
series.setName("Target");
series2.setName("Actual");
xAxis.setLabel("Period");
yAxis.setLabel("£");
yearChart.getData().add(series);
yearChart.getData().add(series2);
yearChart.setCreateSymbols(false);
return yearChart;
}
Answer provided by jewelsea is a perfect solution to this problem.
Thank you, jewelsea.
Use XYChart.Data.setNode(hoverPane) to display a custom node for each data point. Make the hoverNode a container like a StackPane. Add mouse event listeners so that you know when the mouse enters and leaves the node. On enter, place a Label for the value inside the hoverPane. On exit, remove the label from the hoverPane.
There is some example code to demonstrate this technique.
Output of the sample code is shown with the cursor hovered over the 22 node.
Using Tooltip:
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.control.Tooltip;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication250 extends Application
{
#Override
public void start(Stage stage)
{
stage.setTitle("Line Chart Sample");
//defining the axes
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Number of Month");
//creating the chart
final LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
lineChart.setTitle("Stock Monitoring, 2010");
//defining a series
XYChart.Series<Number, Number> series = new XYChart.Series();
series.setName("My portfolio");
//populating the series with data
Random rand = new Random();
TreeMap<Integer, Integer> data = new TreeMap();
//Create Chart data
for (int i = 0; i < 3; i++) {
data.put(rand.nextInt(51), rand.nextInt(51));
}
Set set = data.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " - " + me.getValue());
series.getData().add(new XYChart.Data(me.getKey(), me.getValue()));//Add data to series
}
lineChart.getData().add(series);
//loop through data and add tooltip
//THIS MUST BE DONE AFTER ADDING THE DATA TO THE CHART!
for (Data<Number, Number> entry : series.getData()) {
System.out.println("Entered!");
Tooltip t = new Tooltip(entry.getYValue().toString());
Tooltip.install(entry.getNode(), t);
}
Scene scene = new Scene(lineChart, 800, 600);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}

Reduce number of tick labels on JavaFX xAxis

Up from a certain number of plotted ticks the labels on the xAxis are rotated by 90 degrees into a vertical position.
I would like to keep them horizontal and only plot as many as are fitting to the xAxis.
This shows how it looks and how I would like it to look:
Trying xAxis.setTickLabelRotation() is not showing any effect if there is not enough space to rotate the labels it seems.
I did a work around hiding the xAxis labels, positioning a HBox below the chart and fill it with a few labels that are horizontal. But that is no clean solution and did lead to other issues I would like to avoid.
This example:
JavaFX manually set NumberAxis ticks
shows how to subclass a NumberAxis but I did not make it yet to transfer that to achieve my goal. My idea is to subclass the NumberAxis, overwrite the methods that are responsible for plotting the labels on the xAxis and use a formatter that turns the numbers into the date format to be plotted.
Would that be the right approach and what would be the methods to address? I spent a lot of time going through the sources without success. Any hint into the right direction would be highly appreciated.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LineChartSample extends Application {
#Override
public void start(Stage stage) {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
final LineChart<String, Number> lineChart = new LineChart<String, Number>(xAxis, yAxis);
lineChart.setAnimated(false);
lineChart.setCreateSymbols(false);
XYChart.Series series = new XYChart.Series();
for (int i = 0; i < 100; i+=1)
series.getData().add(new XYChart.Data(msToDateString(i), Math.random()));
Scene scene = new Scene(lineChart, 800, 150);
lineChart.getData().add(series);
stage.setScene(scene);
stage.show();
}
//msToDateString-----------------------------------------------------------------
private static DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS");
private static Date result = new Date();
public static String msToDateString(long milliseconds) {
result.setTime(milliseconds);
return df.format(result);
}
public static void main(String[] args) {
launch(args);
}
}
I know this is an old topic now, but I came across this question while trying to deal with the similar problem myself. I was using custom LineChart class (extended) and had to override layoutPlotChildren() method to be able to put additional shapes to the plot list. To make graph more readable, I wanted to show every second tick on the X axis. In the end, I solved this problem by iterating tick marks and making every second mark invisible. Here is the snippet of the code:
public class MyLineChart extends LineChart<String, Double> {
public MyLineChart (
#NamedArg("xAxis") final Axis<String> xAxis,
#NamedArg("yAxis") final Axis<Double> yAxis) {
super(xAxis, yAxis);
}
...
#Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
...
ObservableList<Axis.TickMark<String>> tickMarks = getXAxis().getTickMarks();
for (int i = 0; i < tickMarks.size(); i++) {
tickMarks.get(i).setTextVisible(i % 2 == 0);
}
}
Hope this helps...

How to make negative values in stacked bar chart start at previous stack?

I want to visualize incoming vs outgoing amounts per month in a stacked bar chart, but also the difference should be immediately visible.
I'm using the following sample code:
public class Statistics extends Application {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
final StackedBarChart<String, Number> sbc = new StackedBarChart<>(xAxis, yAxis);
final XYChart.Series<String, Number> incoming = new XYChart.Series<>();
final XYChart.Series<String, Number> outgoing = new XYChart.Series<>();
#Override
public void start(Stage stage) {
xAxis.setLabel("Month");
xAxis.setCategories(FXCollections.observableArrayList(
Arrays.asList("Jan", "Feb", "Mar")));
yAxis.setLabel("Value");
incoming.setName("Incoming");
incoming.getData().add(new XYChart.Data("Jan", 25601.34));
incoming.getData().add(new XYChart.Data("Feb2", 20148.82));
incoming.getData().add(new XYChart.Data("Mar2", 10000));
outgoing.setName("Outgoing");
outgoing.getData().add(new XYChart.Data("Jan", -7401.85));
outgoing.getData().add(new XYChart.Data("Feb2", -1941.19));
outgoing.getData().add(new XYChart.Data("Mar2", -5263.37));
Scene scene = new Scene(sbc, 800, 600);
sbc.getData().addAll(incoming, outgoing);
stage.setScene(scene);
stage.show();
}
}
Which results in:
As you can see, the negative outgoing values are displayed below zero instead of being subtracted from the positive incoming values, which makes it hard to see the delta between the two.
What I want instead is that a bar for a negative value starts at the top of a bar for a positive value, but as they would overlap then, also apply an offset along the x-axis. At the example of the "Jan" series this should look similar to:
I was playing around with getNode().setTranslateX/Y(), but that does not seem to be a good solution as the translation units is not ticks in the chart, but something else.
How can I create a "stacked" bar chart like in the second image in an elegant way?
Your question is really cool!
So, here I want to share my solution using a BarChart instead of a StackedBarChart. It might be a bit hacky, but it is the only one that worked for me.
The first thing that came to my mind was to just simply take the bar and change its Y coordinate, but unfortunately we cannot access bars directly. So after digging through the source code of XYChart I found that all of the chart's content are located in Group plotContent, but the getter for that is protected. In this situation the one of things to do is to extend the class and increase the scope of method. So (finally), here the code comes:
public class Statistics extends Application {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
// here I use the modified version of chart
final ModifiedBarChart<String, Number> chart = new ModifiedBarChart<>(xAxis, yAxis);
final XYChart.Series<String, Number> incoming = new XYChart.Series<>();
final XYChart.Series<String, Number> outgoing = new XYChart.Series<>();
#Override
public void start(Stage stage) {
xAxis.setLabel("Month");
xAxis.setCategories(FXCollections.observableArrayList(
Arrays.asList("Jan", "Feb", "Mar")));
yAxis.setLabel("Value");
incoming.setName("Incoming");
incoming.getData().add(new XYChart.Data("Jan", 25601.34));
incoming.getData().add(new XYChart.Data("Feb", 20148.82));
incoming.getData().add(new XYChart.Data("Mar", 10000));
outgoing.setName("Outgoing");
// To set the min value of yAxis you can either set lowerBound to 0 or don't use negative numbers here
outgoing.getData().add(new XYChart.Data("Jan", -7401.85));
outgoing.getData().add(new XYChart.Data("Feb", -1941.19));
outgoing.getData().add(new XYChart.Data("Mar", -5263.37));
chart.getData().addAll(incoming, outgoing);
Scene scene = new Scene(chart, 800, 600);
stage.setScene(scene);
stage.show();
// and here I iterate over all plotChildren elements
// note, that firstly all positiveBars come, then all negative ones
int dataSize = incoming.getData().size();
for (int i = 0; i < dataSize; i++) {
Node positiveBar = chart.getPlotChildren().get(i);
// subtract 1 to make two bars y-axis aligned
chart.getPlotChildren().get(i + dataSize).setLayoutY(positiveBar.getLayoutY() - 1);
}
}
// note, that I extend BarChart here
private static class ModifiedBarChart<X, Y> extends BarChart<X, Y> {
public ModifiedBarChart(#NamedArg("xAxis") Axis<X> xAxis, #NamedArg("yAxis") Axis<Y> yAxis) {
super(xAxis, yAxis);
}
public ModifiedBarChart(#NamedArg("xAxis") Axis<X> xAxis, #NamedArg("yAxis") Axis<Y> yAxis, #NamedArg("data") ObservableList<Series<X, Y>> data) {
super(xAxis, yAxis, data);
}
public ModifiedBarChart(#NamedArg("xAxis") Axis<X> xAxis, #NamedArg("yAxis") Axis<Y> yAxis, #NamedArg("data") ObservableList<Series<X, Y>> data, #NamedArg("categoryGap") double categoryGap) {
super(xAxis, yAxis, data, categoryGap);
}
#Override
public ObservableList<Node> getPlotChildren() {
return super.getPlotChildren();
}
}
The result:

BarChart/LineChart - Only the label for the last data point showing

I am not able to get a bar chart or a line chart to show all the labels on the X axis.As you can see in the provided print screen, only the latest datapoint shows its label.
This is when using scene builder. Do I have to have an ObservableList with Strings for the CategoriesAxis ?
I have made a MVCE of my current code:
#FXML
LineChart<String, Integer> lineChart;
#FXML
private Label label;
#FXML
private void handleButtonAction(ActionEvent event) {
XYChart.Series series1 = new XYChart.Series();
series1.getData().add(new XYChart.Data<String, Integer>("austria", 300));
series1.getData().add(new XYChart.Data<String, Integer>("rr", 400));
series1.getData().add(new XYChart.Data<String, Integer>("qq", 3003));
lineChart.getData().addAll(series1);
With your approach, every time you click the button a new series is added to the chart, always with the same data. Note that for the second series you'll get all the labels...
In orther to have just one series, with proper labels, as you've already pointed out, create a global ObservableList, add it at the beginning to the series, and then on Initialize add the series to the chart.
Then if you want to process click events, just add new values to the series, and you'll see the new labels will be added too.
#FXML private LineChart<String, Integer> lineChart;
private final ObservableList<XYChart.Data<String,Integer>> xyList1 =
FXCollections.observableArrayList(
new XYChart.Data<>("austria", 300),
new XYChart.Data<>("rr", 400),
new XYChart.Data<>("qq", 3003));
private final XYChart.Series series1 = new XYChart.Series(xyList1);
#Override
public void initialize(URL url, ResourceBundle rb) {
series1.setName("Name");
lineChart.getData().addAll(series1);
}
#FXML
public void handleButtonAction(ActionEvent e){
// sample new points
series1.getData().add(new XYChart.Data<>("Point "+(series1.getData().size()+1),
new Random().nextInt(3000)));
}
EDIT
If you want to add new series every time you click the button, you can do it as you proposed initially.
But note it seems to be a bug in the first series, and only the last label is shown, IF the chart is animated. To avoid this bug (consider filing it to JIRA), just disable animation and it will work.
If you want animation, you can add a listener to the chart, and set animation once it has at least one series. This will work:
#FXML private LineChart<String, Integer> lineChart;
#Override
public void initialize(URL url, ResourceBundle rb) {
// Workaround to allow animation after series is added
lineChart.getData().addListener(
(ListChangeListener.Change<? extends XYChart.Series<String, Integer>> c) -> {
lineChart.setAnimated(c.getList().size()>1);
});
}
#FXML
public void handleButtonAction(ActionEvent e){
XYChart.Series series1 = new XYChart.Series();
series1.setName("Series "+lineChart.getData().size() );
lineChart.getData().addAll(series1);
series1.getData().add(new XYChart.Data<>("Point "+(series1.getData().size()+1),
new Random().nextInt(3000)));
series1.getData().add(new XYChart.Data<>("Point "+(series1.getData().size()+1),
new Random().nextInt(3000)));
series1.getData().add(new XYChart.Data<>("Point "+(series1.getData().size()+1),
new Random().nextInt(3000)));
}
This is a bug in j8_u20. With the help of the people on the Java Chat we have tested with u20,u25 and u11. This is the result:
U25 bug is visible
U20 bug is visible
U11 bug is not visible
Bug filed to JAVA jira.

Fix X and Y axis widths, JavaFX

How can I achieve fixed Axis width using JavaFx line graph.
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.stage.Stage;
public class Axis extends Application
{
private Timeline animation;
public static void main(final String[] args)
{
launch(args);
}
#Override
public void start(final Stage stage) throws Exception
{
final NumberAxis x = new NumberAxis();
final NumberAxis y = new NumberAxis();
x.setAutoRanging(false);
y.setAutoRanging(false);
final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(x, y);
// final Series series = new LineChart.Series<Number, Number>();
//
// series.getData().add(new XYChart.Data(20, 23));
// series.getData().add(new XYChart.Data(35, 14));
// series.getData().add(new XYChart.Data(43, 15));
// series.getData().add(new XYChart.Data(60, 24));
// series.getData().add(new XYChart.Data(10, 34));
//
// lineChart.getData().add(series);
lineChart.setPrefHeight(10);
lineChart.setPrefWidth(10);
lineChart.setMinHeight(10);
lineChart.setMinWidth(10);
lineChart.setMaxHeight(10);
lineChart.setMaxWidth(10);
final Scene scene = new Scene(lineChart, 800, 800);
stage.setScene(scene);
stage.show();
}
#Override
public void stop()
{
animation.pause();
}
}
I would like the grid (sample marked in red) not to scale when I resize the window. Currently the grid resizes when the window is resized as shown below
I am not able to achieve what I need using the minWidth and maxWidth API's
Preventing resizing of a Graph
You can prevent the graph resizing by setting it's preferred, min and max sizes:
lineChart.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
lineChart.setPrefSize(800, 600);
lineChart.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
The only exception to this is when the chart is the root of the scene, in which case you should wrap the chart in a Pane or Group to prevent it being resized to fit the scene (because of a layout quirk in the JavaFX 8 rendering logic).
Also note, wrapping any resizable node a Group will size the node (excluding transforms and effects) to it's preferred dimensions and never change them.
Unfortunately, setting the preferred size of the graph isn't exactly the same as setting the preferred sizes of the graph's axes directly, as it makes the entire chart that size, not a specific axis line, which is probably what you are looking for with your question.
Preventing resizing of a Graph Axis
I don't know how to do this.
You might think you could do the following:
xAxis.setMinWidth(Control.USE_PREF_SIZE);
xAxis.setPrefWidth(800);
xAxis.setMaxWidth(Control.USE_PREF_SIZE);
But this doesn't work in Java 8 when the axis is embedded inside a chart. This is because the XYChart layout routine ignores the preferred, min and max sizes of it's axes when it lays out the chart contents.
This is perhaps a bug, so you might want to log it as such at https://javafx-jira.kenai.com.

Resources