Reputation: 33
How can I open a new bar chart window (JavaFX) when I am clicking on a button (inside a swing jar-application)?
I have already a functioning GUI with a button handler, but I can't connect the example from Oracle (http://docs.oracle.com/javafx/2/charts/bar-chart.htm) with the button so that the bar chart opens when I click the button.
I am working with the desktop Java Development Kit (Version 7 Update 40, 64-bit) and Eclipse Juno.
Basically I tried this:
...
BarChartSample chart = new BarChartSample();
Stage stage = new Stage();
chart.start(stage);
...
Upvotes: 3
Views: 1748
Reputation: 866
The easiest way is to do it with your window made in swing (the one containing the chart).
If you do that the code would look something like this:
JFrame frame = new JFrame("Chart");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
and after that you should add the chart to the fxPanel, since javaFx is thread safe you will have to use the Platform.runLater:
Platform.runLater(new Runnable() {
@Override
public void run() {
BarChartSample chart = new BarChartSample();
fxPanel.setScene(new Scene(chart));
}
});
Hope it helps!
Edit:
The chart should something like this:
BarChart<String, Number> chart = getChart();
The previous line of code should be in a:
Platform.runLater(new Runnable() {
@Override
public void run() {
//CODE HERE
}
});
Again, this is cause javaFx is thread safe.
and the method to create it:
public BarChart<String, Number> getChart() {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
final BarChart<String, Number> bc = new BarChart<String, Number>(xAxis,
yAxis);
bc.setTitle("Country Summary");
xAxis.setLabel("Country");
yAxis.setLabel("Value");
XYChart.Series series1 = new XYChart.Series();
series1.setName("2003");
series1.getData().add(new XYChart.Data(austria, 25601.34));
series1.getData().add(new XYChart.Data(brazil, 20148.82));
series1.getData().add(new XYChart.Data(france, 10000));
series1.getData().add(new XYChart.Data(italy, 35407.15));
series1.getData().add(new XYChart.Data(usa, 12000));
XYChart.Series series2 = new XYChart.Series();
series2.setName("2004");
series2.getData().add(new XYChart.Data(austria, 57401.85));
series2.getData().add(new XYChart.Data(brazil, 41941.19));
series2.getData().add(new XYChart.Data(france, 45263.37));
series2.getData().add(new XYChart.Data(italy, 117320.16));
series2.getData().add(new XYChart.Data(usa, 14845.27));
XYChart.Series series3 = new XYChart.Series();
series3.setName("2005");
series3.getData().add(new XYChart.Data(austria, 45000.65));
series3.getData().add(new XYChart.Data(brazil, 44835.76));
series3.getData().add(new XYChart.Data(france, 18722.18));
series3.getData().add(new XYChart.Data(italy, 17557.31));
series3.getData().add(new XYChart.Data(usa, 92633.68));
Scene scene = new Scene(bc, 800, 600);
bc.getData().addAll(series1, series2, series3);
return bc;
}
Upvotes: 1