JavaFX图表变量范围

时间:2016-01-05 23:27:10

标签: java javafx charts javafx-8

final CategoryAxis yAxis = new CategoryAxis();
final NumberAxis zAxis = new NumberAxis(); 

if (cbTypeGraphView.equals("Bar Chart")) {
    BarChart<String, Number> chart = new BarChart<String, Number>(yAxis,xAxis);
}
if (cbTypeGraphView.equals("Line Chart")) {
    LineChart<String, Number> chart = new LineChart<String, Number>(yAxis,xAxis);
}

AnchorPane.setTopAnchor(chart, 110d);
AnchorPane.setLeftAnchor(chart, 10d);
AnchorPane.setRightAnchor(chart, 5d);
AnchorPane.setBottomAnchor(chart, 50d);

chart变量在if语句之外丢失范围我想知道如何解决这个问题,以便chart不会在if语句之外丢失范围。我正在考虑使用它的父类XYChart类。我不确定如何将BarChartLineChart添加到XYChart

1 个答案:

答案 0 :(得分:0)

你可以做到

final CategoryAxis yAxis = new CategoryAxis();
final NumberAxis zAxis = new NumberAxis(); 

XYChart<String, Number> chart = null ;

if (cbTypeGraphView.equals("Bar Chart")) {
    chart = new BarChart<String, Number>(yAxis,xAxis);
}
if (cbTypeGraphView.equals("Line Chart")) {
    chart = new LineChart<String, Number>(yAxis,xAxis);
}

AnchorPane.setTopAnchor(chart, 110d);
AnchorPane.setLeftAnchor(chart, 10d);
AnchorPane.setRightAnchor(chart, 5d);
AnchorPane.setBottomAnchor(chart, 50d);

您应该处理不执行if语句的情况,以避免空指针异常。