首页 > 解决方案 > 如何“自动调整”javafx 中的类别轴标签?

问题描述

我正在用 JavaFX 编写一个小直方图。我使用 BarChart 作为节点并将 XYChart 系列添加到 BarChart。在我发现这个之前,我的代码运行良好:

在原点分组的类别标签图片

标签相互重叠。

然后当我手动调整窗口大小时:

调整窗口大小后正确定位的类别标签图片

所以,我的问题是如何在不手动进行的情况下使其自行调整?

这是我的代码的简要视图:

    //  Make an axis for x and one for y. Then, create a chart for the histogram by using x and y axis.
    final CategoryAxis xAxis = new CategoryAxis();
    final NumberAxis yAxis = new NumberAxis();
    final BarChart<String,Number>histogramChart = new BarChart<String,Number>(xAxis,yAxis);
    BorderPane myBorderPane = new BorderPane();   //  Use a border pane for the histogram and the button. 
    Button btEnter = new Button("ENTER");
    TextField tfDirectory = new TextField();
    Scanner input;
    XYChart.Series seriesOfAlphabet = new XYChart.Series();
    HBox hbxDirectoryAndButton = new HBox();
    //  A final string array for the arphabet
    final static String[] alphabets= {"A","B","C","D","E","F"
                                     ,"G","H","I","J","K","L"
                                     ,"M","N","O","P","Q","R"
                                     ,"S","T","U","V","W","X"
                                     ,"Y","Z"};

    //  Main to launch the application
    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        //  Set the title of the stage
        primaryStage.setTitle("Histogram Of Occurences of Letters by Luckas(YingHong Huang");
        //  Set the title of the chart
        histogramChart.setTitle("Histogram");
        xAxis.setLabel("Alphets");          // Set label of the xAxis
        yAxis.setLabel("Occurences");       // Set the label of yAxis
        tfDirectory.setLayoutY(20);         //  Set the height of the text field for the file input
        tfDirectory.setLayoutX(100);        //  Set the length of the text field for the file input
        seriesOfAlphabet.setName("Occurences");
        btEnter.setOnAction(e->{
            openFile();
        });    
        histogramChart.getData().add(seriesOfAlphabet);
        hbxDirectoryAndButton.getChildren().addAll(tfDirectory,btEnter);     
        hbxDirectoryAndButton.setSpacing(10);
        myBorderPane.setCenter(histogramChart);
        myBorderPane.setBottom(hbxDirectoryAndButton);
        myBorderPane.setPadding(new Insets(5,5,5,5));
        Scene histogramScene = new Scene(myBorderPane,1500,700);
        primaryStage.setScene(histogramScene);
        primaryStage.show();
    }

标签: javajavafxbar-chart

解决方案


我今天遇到了同样的问题。我使用 Javafx Scene Builder 并在属性中取消选择“动画”解决了这个问题。希望能帮助到你。


推荐阅读