Simple JavaFX HelloWorld Does Not Work

2020-04-21 01:15发布

I am still getting this error over and over again: Error resolving onAction='#sayHelloWorld', either the event handler is not in the Namespace or there is an error in the script.. I've googled in the Internet for a solution but nothing works, surely is a small detail somrwhere I'm missing since I'm new to JAvaFX, this is my first HelloWorld app. Anyways, this is the code I'm using:

sample.fxml:

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

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>

<GridPane alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8"
          xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.SampleController">
    <columnConstraints>
        <ColumnConstraints />
        <ColumnConstraints />
    </columnConstraints>
    <rowConstraints>
        <RowConstraints />
        <RowConstraints />
    </rowConstraints>
   <children>
       <Button text="Load News"
               GridPane.columnIndex="1" GridPane.rowIndex="1"
               onAction="#sayHelloWorld"/>
       <Label GridPane.columnIndex="0" GridPane.rowIndex="1" fx:id="helloWorld"/>
   </children>
</GridPane>

And SampleController.java

package sample;

import javafx.scene.control.Label;

import java.awt.event.ActionEvent;

public class SampleController {
    public Label helloWorld;

    public void sayHelloWorld(ActionEvent actionEvent) {
    }
}

Any help would be appreciated.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-04-21 01:56

Found the problem. It was the ActionEvent class, the class declared in the import section is not a JavaFX class, so using the correct one makes it work. This is the final code:

package sample;

//import java.awt.event.ActionEvent;  //This was the error!
import javafx.event.ActionEvent;
import javafx.scene.control.Label;

public class SampleController {
    public Label helloWorld;

    public void sayHelloWorld(ActionEvent actionEvent) {
        helloWorld.setText("Hello World!!");
    }
}

No annotations are required.

查看更多
Evening l夕情丶
3楼-- · 2020-04-21 01:58

You are missing the @FXML anotation tag to make the content accesible to markup

    public class SampleController 
    {
        @FXML
        public Label helloWorld;

        @FXML
        public void sayHelloWorld(ActionEvent actionEvent) 
        {
            //....
        }
    }
查看更多
成全新的幸福
4楼-- · 2020-04-21 01:59

Add the fxml annotation like this

    package sample;

import javafx.scene.control.Label;

import java.awt.event.ActionEvent;

public class SampleController {
    public Label helloWorld;
    @FXML
    public void sayHelloWorld(ActionEvent actionEvent) {
    }
}

without tha annotation it canot be found

查看更多
登录 后发表回答