2016-01-12 33 views
0

我使用擴展的BarChart類在豎線上添加垂直線和文本。這工作正常,但我想在水平線的右上角顯示一個小文本。如何在JavaFX的水平線上添加文本BarChart

我想這沒有成功:

public void addHorizontalValueMarker(Data<X, Y> marker) { 
    Objects.requireNonNull(marker, "the marker must not be null"); 
    if (horizontalMarkers.contains(marker)) return; 
    Line line = new Line(); 
    line.setStroke(Color.RED);   
    marker.setNode(line); 
    getPlotChildren().add(line); 

    // Adding a label 
    Node text = new Text("average"); 
    nodeMap.put(marker.getNode(), text); 
    getPlotChildren().add(text); 

    horizontalMarkers.add(marker); 
} 

@Override 
protected void layoutPlotChildren() { 
    super.layoutPlotChildren(); 
    for (Node bar : nodeMap.keySet()) { 
     Node text = nodeMap.get(bar); 
     text.relocate(bar.getBoundsInParent().getMinX() + bar.getBoundsInParent().getWidth()/2 - text.prefWidth(-1)/2, bar.getBoundsInParent().getMinY() - 30); 
    } 
    for (Data<X, Y> horizontalMarker : horizontalMarkers) { 
     Line line = (Line) horizontalMarker.getNode(); 
     line.setStartX(0); 
     line.setEndX(getBoundsInLocal().getWidth()); 
     line.setStartY(getYAxis().getDisplayPosition(horizontalMarker.getYValue()) + 0.5); // 0.5 for crispness 
     line.setEndY(line.getStartY()); 
     line.toFront(); 
    } 

} 

我做錯了嗎?

回答

1

您需要在移動標記後移動文本。即你的代碼在所需位置集成:

for (Data<X, Y> horizontalMarker : horizontalMarkers) { 
     Line line = (Line) horizontalMarker.getNode(); 
     line.setStartX(0); 
     line.setEndX(getBoundsInLocal().getWidth()); 
     line.setStartY(getYAxis().getDisplayPosition(horizontalMarker.getYValue()) + 0.5); // 0.5 for crispness 
     line.setEndY(line.getStartY()); 
     line.toFront(); 

     Node text = nodeMap.get(line); 
     text.relocate(line.getBoundsInParent().getMinX() + line.getBoundsInParent().getWidth()/2 - text.prefWidth(-1)/2, line.getBoundsInParent().getMinY() - 30); 
    } 

順便說一句,我建議創建一個專用標記類持有線和文字,而不是使用「寬鬆」的地圖。

相關問題