1.构造器和初始化方法的执行顺序
测试Controler中构造器和初始化方法的执行顺序:
public class MainViewController {
public MainViewController() {
System.out.println("first");
}
@FXML
public void initialize() {
System.out.println("second");
}
}
结果为:
调用构造函数,填充任何@FXML注释字段,调用initialize()。构造函数无法访问引用在.fxml文件中定义的组件的@FXML字段,而initialize()可以访问它们。
2.BarChar无法显示图形
Main;javafx.collections.FXCollections;javafx.event.ActionEvent;javafx.fxml.Initializable;javafx.scene.chart.BarChart;javafx.scene.chart.CategoryAxis;javafx.scene.chart.NumberAxis;javafx.scene.chart.XYChart;javafx.scene.layout.BorderPane;java.net.URL;java.util.Arrays;java.util.ResourceBundle;Controller Initializable { BarChart<String, Number> ; CategoryAxis ; NumberAxis ; BorderPane ; initialize(URL location, ResourceBundle resources) { = CategoryAxis(); .setCategories(FXCollections.<String>(Arrays.(, , , ))); .setLabel(); = NumberAxis(); .setLabel(); = BarChart<>(, ); .setTitle(); XYChart.Series<String, Number> series1 = XYChart.Series<>(); series1.setName(); series1.getData().add(XYChart.Data<>(, )); series1.getData().add(XYChart.Data<>(, )); series1.getData().add(XYChart.Data<>(, )); series1.getData().add(XYChart.Data<>(, )); XYChart.Series<String, Number> series2 = XYChart.Series<>(); series2.setName(); series2.getData().add(XYChart.Data<>(, )); series2.getData().add(XYChart.Data<>(, )); series2.getData().add(XYChart.Data<>(, )); series2.getData().add(XYChart.Data<>(, )); XYChart.Series<String, Number> series3 = XYChart.Series<>(); series3.setName(); series3.getData().add(XYChart.Data<>(, )); series3.getData().add(XYChart.Data<>(, )); series3.getData().add(XYChart.Data<>(, )); series3.getData().add(XYChart.Data<>(, )); .getData().addAll(series1, series2, series3); } settingBtnClick(ActionEvent actionEvent) { }}执行上述程序时,无法显示条状图,经过看视频出问题所在,xAxis,yAxis,和Production不能在初始化方法中再此创建实例。FXML通过反射已经创建过实例,在初始化方法中直接使用即可。去掉三个的new方法后正常显示。