控制器" classname"没有事件位" methodname"

时间:2016-05-05 13:49:14

标签: java javafx fxml

我收到此错误

控制器"类名"没有事件插槽" methodname"

如果我添加" /"在fx中应用之前:controller =" application.MainController"> 这个错误可以创造 class无法加载

/Users/myname/Documents/workspace/Javafx%20tesr/bin/application/Main.fxml:7

这里是xml文件

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="450" prefWidth="500"     xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1"     fx:controller="application.MainController">
   <children>
      <Button fx:id="genratebutton" layoutX="160.0" layoutY="225.0"     mnemonicParsing="false" onAction="#generaterandom" prefHeight="27.0"     prefWidth="180.0" text="generate random" />
      <Label fx:id="myMessage" layoutX="138.0" layoutY="104.0"     prefHeight="89.0" prefWidth="225.0" />
   </children>
</AnchorPane>

(抱歉,GUI只知道摇摆的基础知识)

这是主要的课程

package application;

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


public class Main extends Application {
@Override
public void start(Stage primaryStage) {
    try {
Parent root=FXMLLoader.load(getClass().getClassLoader().getResource("/Main.fxml"));

  Scene scene = new Scene(root,400,400);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    } 

    catch(Exception e) {
        e.printStackTrace();
        System.exit(0);

    }
}

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

这是另一个我想调用方法的类

package application;


import java.util.Random;
import javafx.event.ActionEvent;

import javafx.fxml.FXML;
import javafx.scene.control.Label;


public class MainController {

@FXML
private Label myMessage;
void generaterandom (ActionEvent event){
    Random rand=new Random();
    int myrand=rand.nextInt(50)+1;
    myMessage.setText(Integer.toString(myrand));
    System.out.println(Integer.toString(myrand));


}

}

eclipse explorer view

1 个答案:

答案 0 :(得分:2)

由于控制器方法不是public,您需要对其进行注释@FXML

public class MainController {

    @FXML
    private Label myMessage;

    @FXML
    void generaterandom (ActionEvent event){
        Random rand=new Random();
        int myrand=rand.nextInt(50)+1;
        myMessage.setText(Integer.toString(myrand));
        System.out.println(Integer.toString(myrand));


    }

}