我目前正在編寫一個名爲Farkle的遊戲。我想爲每個代表骰子的矩形添加一個OnMouseClick事件。javafx rectangle onmouseclick event(fxml)
我的問題是矩形不能識別MouseEvent。我使用Scene Builder構建了我的GUI。這是我的FXML代碼的摘錄:
<Rectangle fx:id="recDice1" arcHeight="5.0" arcWidth="5.0" fill="WHITE"
height="40.0" onMouseClicked="#recDice1_OnMouseClicked" stroke="BLACK"
strokeType="INSIDE" width="40.0" GridPane.halignment="CENTER"
GridPane.valignment="CENTER" />
的矩形處於GridPane和GridPane被下令在BorderPane的左側。
這是我的Java代碼的摘錄:
@FXML private Rectangle recDice1;
@FXML public void recDice1_OnMouseClicked(MouseEvent event){
System.out.println("Funktioniert!");
}
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Farkle");
initLayout();
}
public void initLayout(){
try {
//Erstelle FXMLLoader
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("../gui/FarkleGUI.fxml"));
loader.setController(new FarkleControl());
rootLayout = (BorderPane) loader.load();
//Lade Szene
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
//Setze Grösse der Stage (Somit entfallen Margins)
primaryStage.sizeToScene();
//Zeige Szene
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
進口:
package java2.farkle.mlz.control;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
就像我在一開始的矩形不承認的MouseEvent說。我嘗試了與按鈕相同,它工作正常。
如果您正在使用Scenebuilder,可以假定您正在使用MVC創意。但是,在你的代碼中你不是。您使用Scenebuilder更改的FXML文件具有您應該使用的控制器文件。在MVC中幾乎所有情況下,你都不應該對Main文件做任何事情。您的@FXML代碼應該位於與FXML文件關聯的控制器中。 – Sedrick