如何确定折线图原点的像素位置?

时间:2012-09-25 17:30:16

标签: charts javafx-2 linechart

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

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

2 个答案:

答案 0 :(得分: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 + "]";
}

答案 1 :(得分: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();