[英]JavaFx @FXML Pagination injected to my controller class can't be modified
[英]Why doesn't my fxml controller class move my button?
我目前正在使用3個類:ButtonMove.java,MainController.java和Main.fxml。 我一直在嘗試使用SceneBuilder創建用戶界面,並想向對象添加運動。 我試過讓此按鈕移動,但無濟於事。 舞台啟動,我看到按鈕,但它仍然靜止不動。
package TestClasses;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class ButtonMove extends Application
{
@Override
public void start(Stage stage) throws Exception {
// TODO Auto-generated method stub
Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
上面的類ButtonMove.java僅加載fxml文件Main.fxml並啟動舞台。 下面是Main.fxml控制器文件,由於某種原因,該文件一直告訴我從未使用過javafx.fxml.FXML。
package TestClasses;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.TranslateTransition;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.util.Duration;
public class MainController implements Initializable
{
private Button button;
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
TranslateTransition transition = new TranslateTransition();
transition.setDuration(Duration.seconds(4));
transition.setNode(button);
transition.setToY(-200);
transition.play();
}
}
這只是SceneBuilder生成的fxml文件。
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.StackPane?>
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
<children>
<AnchorPane prefHeight="200.0" prefWidth="200.0">
<children>
<Button id="button" layoutX="274.0" layoutY="310.0" mnemonicParsing="false" text="CLICK" />
</children>
</AnchorPane>
</children>
</StackPane>
由於某種原因,它一直告訴我從未使用過javafx.fxml.FXML。
這是因為您沒有在代碼中的任何地方使用@FXML
批注。
要將fxml連接到控制器,您需要
通過注釋使應該注入的字段對FXMLLoader
可見:
@FXML private Button button;
通過將fx:controller
屬性添加到根元素來指定要與fxml一起使用的控制器類:
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="TestClasses.MainController">
或通過在調用FXMLLoader.load
之前指定控制器實例
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml")); loader.setController(new MainController()); Parent root = loader.load();
為要注入到控制器的對象指定fx:id
屬性:
<Button fx:id="button" layoutX="274.0" layoutY="310.0" mnemonicParsing="false" text="CLICK" />
在此處添加FXML標簽:
@FXML
private Button button;
否則,按鈕不會初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.