我有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;
-
通过将
来指定要与FXML一起使用的控制器类:fx:controller
属性添加到root元素:<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;
否则该按钮不会初始化。