我修改了Oracle网站的条形图示例,并将每个系列的条形减少到1。不幸的是,条形图不会位于刻度线上方。
有没有人知道如何让条形水平居中于刻度线上方?
以下是代码:
public class BarChartDemo extends Application {
final static String austria = "Austria";
final static String brazil = "Brazil";
final static String france = "France";
@Override
public void start(Stage stage) {
stage.setTitle("Bar Chart Sample");
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));
XYChart.Series series2 = new XYChart.Series();
series2.setName("2004");
series2.getData().add(new XYChart.Data(brazil, 41941.19));
XYChart.Series series3 = new XYChart.Series();
series3.setName("2005");
series3.getData().add(new XYChart.Data(france, 18722.18));
Scene scene = new Scene(bc, 800, 600);
bc.getData().addAll(series1, series2, series3);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
这就是它的样子:
非常感谢!
答案 0 :(得分:3)
<强>问题强>
BarChart的问题在于您要添加3个系列,但每个系列中只有一个唯一的国家/地区。 BarChart固有地为另外两个系列留出了空间。
<强>解决方案强>
实现此目的的正确方法是使用一个 XYChart.Series
,然后为每个条添加颜色。这是一个示例应用程序,它也是如此。
public class BarChartDemo extends Application {
final static String austria = "Austria";
final static String brazil = "Brazil";
final static String france = "France";
@Override
public void start(Stage stage) {
stage.setTitle("Bar Chart Sample");
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");
final XYChart.Data<String, Number> dataAustria = new XYChart.Data(austria, 25601.34);
final XYChart.Data<String, Number> dataBrazil = new XYChart.Data(brazil, 41941.19);
final XYChart.Data<String, Number> dataFrance = new XYChart.Data(france, 35000.19);
series1.getData().add(dataAustria);
series1.getData().add(dataBrazil);
series1.getData().add(dataFrance);
Scene scene = new Scene(bc, 800, 600);
bc.getData().addAll(series1);
stage.setScene(scene);
stage.show();
dataAustria.getNode().setStyle("-fx-bar-fill: CHART_COLOR_1;");
dataBrazil.getNode().setStyle("-fx-bar-fill: CHART_COLOR_2;");
dataFrance.getNode().setStyle("-fx-bar-fill: CHART_COLOR_3;");
}
public static void main(String[] args) {
launch(args);
}
}
输出看起来像你要找的东西:
注意:您需要在节点显示在舞台上后将样式应用于节点。或者,您可以使用xyChartData.nodeProperty().addListener()
并在其中应用样式。
dataAustria.nodeProperty().addListener((ov, oldNode, newNode) -> {
if(null != newNode) {
newNode.setStyle("-fx-bar-fill: red;");
}
});