在javafx中的fxml文件中填充类别轴

populating a category axis in fxml file in javafx

我在 fxml 文件中有一个 scatter chart,我想向其类别轴添加一些值。我想在 fxml 文件中执行此操作。如何将这些值添加到 javafx 中的 category axis

<ScatterChart fx:id="scatterChart" title="title 1" titleSide="BOTTOM" BorderPane.alignment="CENTER">
    <xAxis  fx:id="xaxis">
        <NumberAxis lowerBound="-1.0" minorTickCount="0" side="BOTTOM" upperBound="1.0" />
    </xAxis>
    <yAxis>
        <CategoryAxis side="LEFT" />
    </yAxis  fx:id="yaxis">
</ScatterChart>

CategoryAxis 有一个 setCategories() method taking an ObservableList<String>, so you need a <categories> element inside the <CategoryAxis> element. Creating and populating an ObservableList<String> takes a little digging into the FXML documentation,但基本上你需要 fx:factory 来创建列表,fx:value 来创建 String 个实例:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.chart.ScatterChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.chart.CategoryAxis?>

<?import javafx.collections.FXCollections?>

<?import java.lang.String?>

<BorderPane xmlns:fx="http://javafx.com/fxml/1">
    <center>
        <ScatterChart fx:id="scatterChart" title="title 1"
            titleSide="BOTTOM" BorderPane.alignment="CENTER">
            <xAxis >
                <NumberAxis fx:id="xaxis" lowerBound="-1.0" minorTickCount="0" side="BOTTOM"
                    upperBound="1.0" />
            </xAxis>
            <yAxis>
                <CategoryAxis fx:id="yaxis" side="LEFT" >
                    <categories>
                        <FXCollections fx:factory="observableArrayList">
                            <String fx:value="One"/>
                            <String fx:value="Two"/>
                            <String fx:value="Three" />
                            <String fx:value="Four" />
                            <String fx:value="Five" />                          
                        </FXCollections>
                    </categories>
                </CategoryAxis>
            </yAxis >
        </ScatterChart>
    </center>
</BorderPane>

测试class:

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class CategoryAxisExample extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {
        primaryStage.setScene(new Scene(FXMLLoader.load(getClass().getResource("ScatterChart.fxml")), 600, 600));
        primaryStage.show();
    }

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

截图: