JavaFX - 如何定位轴标签以避免与刻度线冲突

时间:2015-08-25 20:57:18

标签: javafx javafx-2

下面的代码是一个简单的折线图,其中yAxis刻度标签在字符长度/宽度方面很宽。默认情况下定位的yAxis标签太靠近yAxis,这意味着文本与刻度标记冲突。是否可以通过增加标签和轴之间的间隙来避免这种情况?

enter image description here

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;

public class Example extends Application {

    @Override
    public void start(Stage stage) {
        final NumberAxis xAxis = new NumberAxis(0, 10, 2);
        final NumberAxis yAxis = new NumberAxis(1.3378, 1.3390, 0.0001);
        xAxis.setLabel("xAxis");
        yAxis.setLabel("yAxis");
        yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis){
            @Override public String toString(Number object){
                return String.format("%1.4f", object); }
        });

        final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
        XYChart.Series series = new XYChart.Series();

        final XYChart.Data d1 = new XYChart.Data(0.0,1.3379);
        final XYChart.Data d2 = new XYChart.Data(2.0,1.3387);
        final XYChart.Data d3 = new XYChart.Data(2.5,1.3385);
        final XYChart.Data d4 = new XYChart.Data(3.5,1.3387);
        final XYChart.Data d5 = new XYChart.Data(8.0,1.3378);
        final XYChart.Data d6 = new XYChart.Data(9.5,1.3388);

        series.getData().addAll(d1, d2, d3, d4, d5, d6);
        lineChart.getData().add(series);
        lineChart.setLegendVisible(false);

        final Scene scene = new Scene(lineChart, 400, 300);
        stage.setScene(scene);
        stage.show();
    }


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

2 个答案:

答案 0 :(得分:2)

我认为不可能重新定位“yAxis”标签或增加差距,但您可能希望使用以下解决方法来避免文本混淆:

lineChart.getYAxis().setTickLabelRotation(-90);

您将获得以下图表: enter image description here

答案 1 :(得分:1)

可以找到轴的标签。

例如,要将Label 10 Pixel移动到左侧,只需使用:

lineChart.getYAxis()
       .lookup(".axis-label")
       .setStyle("-fx-label-padding: -10 0 0 0;");