1

JavaFX LineChart 由绘图区域和轴组成。由于坐标区渲染使用了一些显示空间,因此折线图中原点的位置不是 (0, 0)。如何获得相对于折线图本身位置的这个位置?

我想计算绘图区域中一个点相对于折线图位置的位置。x 轴和 y 轴的getDisplayPosition方法提供了相对于原点的方法,但我看不到获取原点位置的明显方法。

4

2 回答 2

3

axis.getDisplayPosition(val)方法提供给定轴val在绘图区域中相对于绘图区域左上角的像素位置。您可以使用 getDisplayPosition() 方法计算任意点相对于折线图原点的位置。请记住,当调整折线图的大小时,这些像素位置会有所不同。

@Override
public void start(Stage stage) {
    stage.setTitle("Line Chart Sample");
    //defining the axes
    final NumberAxis xAxis = new NumberAxis();
    final NumberAxis yAxis = new NumberAxis();
    xAxis.setLabel("Number of Month");
    //creating the chart
    final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);

    lineChart.setTitle("Stock Monitoring, 2010");
    //defining a series
    XYChart.Series series = new XYChart.Series();
    series.setName("My portfolio");
    //populating the series with data
    series.getData().add(new XYChart.Data(-1, 4));
    series.getData().add(new XYChart.Data(0, 2));
    series.getData().add(new XYChart.Data(1, -2));
    series.getData().add(new XYChart.Data(5, 1));

    Scene scene = new Scene(lineChart, 800, 400);
    lineChart.getData().add(series);

    System.out.println("");
    stage.setScene(scene);
    stage.show();

    System.out.println("Points in linechart  ->   Pixel positions relative to the top-left corner of plot area: ");
    System.out.println("(0,0)                ->   " + getFormatted(xAxis.getDisplayPosition(0), yAxis.getDisplayPosition(0)));
    // Same as
    // System.out.println("(0,0) " + getFormatted(xAxis.getZeroPosition(), yAxis.getZeroPosition()));
    System.out.println("(-1,4)               ->   " + getFormatted(xAxis.getDisplayPosition(-1), yAxis.getDisplayPosition(4)));
    System.out.println("(1,-2)               ->   " + getFormatted(xAxis.getDisplayPosition(1), yAxis.getDisplayPosition(-2)));
    System.out.println("(-1.5,5) origin of plot area ->   " + getFormatted(xAxis.getDisplayPosition(-1.5), yAxis.getDisplayPosition(5)));

    System.out.println("Note: These pixel position values will change when the linechart's size is \n changed through window resizing for example.");
}

private String getFormatted(double x, double y) {
    return "[" + "" + x + "," + y + "]";
}
于 2012-10-05T12:15:32.467 回答
3

更好的观察方法是通过如下chart.lookup命令获取绘图区域:

//gets the display region of the chart
Node chartPlotArea = chart.lookup(".chart-plot-background");
double chartZeroX = chartPlotArea.getLayoutX();
double chartZeroY = chartPlotArea.getLayoutY();
于 2013-06-18T09:48:15.520 回答