2013-03-12 48 views
0

这里是我的代码生成10条不同颜色的条。我想分别添加图例,但它只显示黄色的传说我可以改变它的颜色,但我想要3传说。如何为单个系列条形图添加3个图例? JAVAFX

我认为它只显示1种颜色,因为只有1个系列。是否可以为单个系列添加超过1个图例?

输出:enter image description here

,或者如果我能像传说中添加此图片我图的中间偏左

enter image description here

我需要如何条形图显示图像或如何创建3单个系列条形图的不同标签

import javafx.application.Application; 
import javafx.beans.value.*; 
import javafx.scene.*; 
import javafx.scene.chart.*; 
import javafx.stage.Stage; 

public class DynamicallyColoredBarChart extends Application { 

    @Override 
    public void start(Stage stage) { 
     final CategoryAxis xAxis = new CategoryAxis(); 
     xAxis.setLabel("Bars"); 
     final NumberAxis yAxis = new NumberAxis(); 
     yAxis.setLabel("Value"); 

     final BarChart<String, Number> bc = new BarChart<>(xAxis, yAxis); 
     bc.setLegendVisible(false); 

     XYChart.Series series1 = new XYChart.Series(); 

     for (int i = 0; i < 10; i++) { 
      // change color of bar if value of i is >5 than red if i>8 than blue 
      final XYChart.Data<String, Number> data = new XYChart.Data("Value " + i, i); 
      data.nodeProperty().addListener(new ChangeListener<Node>() { 
       @Override 
       public void changed(ObservableValue<? extends Node> ov, Node oldNode, Node newNode) { 
        if (newNode != null) { 
         if (data.getYValue().intValue() > 8) { 
          newNode.setStyle("-fx-bar-fill: navy;"); 
         } else if (data.getYValue().intValue() > 5) { 
          newNode.setStyle("-fx-bar-fill: red;"); 
         } 
        } 
       } 
      }); 
      series1.getData().add(data); 
     } 
     bc.getData().add(series1); 
     stage.setScene(new Scene(bc)); 
     stage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
+0

并且可以在条形图的左侧添加一个图像,显示图例? – H4SN 2013-03-12 10:33:50

回答

1

要将图像放在左侧,您可以添加图像和cha rt to HBox:

HBox root = new HBox(5); 
root.getChildren().addAll(image, bc); 
stage.setScene(new Scene(root)); 
相关问题