我有2个FXML文件,有2个控制器。每个FXML文件都有自己的控制器。第一个场景有一个按钮,可以将您带到第二个场景。现在我的问题是,如何开始执行命令" label.setText(" Hello There \ n");"在我的第二个控制器中没有做任何额外的ActionEvent,而不是从scene1点击按钮将我带到scene2。
MainController:
public void startNewScene() throws IOException {
root = FXMLLoader.load(getClass().getResource("FXML.fxml"));
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.show();
}
根据以下评论中的示例的第二个控制器来自" ItachiUchiha"
public class MyController implements Initializable {
@FXML private Button button;
@FXML private Label label;
@FXML
@Override
public void initialize(URL location, ResourceBundle resources) {
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
label.setText("hello there, you clicked me");
}
}
);
}
}
现在第二个场景上传但没有任何内容输出到屏幕或控制台。但是当我点击场景上的按钮时,一切正常。
所以我试着设置&#34; onMouseClicked&#34;和&#34; onAction&#34;初始化和/或处理标签和按钮,但我得到错误&#34;找不到处理程序方法。&#34;在FXML文件中
FXML文件:
<GridPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ciacv.MyController">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<Label fx:id="label" />
<Button fx:id="button" mnemonicParsing="false" text="Button" GridPane.columnIndex="1" />
</children>
</GridPane>
答案 0 :(得分:1)
fxml中按钮的fx:id
为butn1
,在控制器中,您正在尝试使用声明注入按钮
@FXML private Button button;
您需要使用在fxml中声明的相同fx:id
来正确地将对象注入其引用,即
@FXML private Button butn1;
修改 - 根据评论
您需要设置Scene on the Stage
public void startNewScene() throws IOException {
root = FXMLLoader.load(getClass().getResource("FXML.fxml"));
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.show();
}
编辑 - 2
当fxml加载时,你没有写任何东西来设置标签中的文本。
你刚刚写过
label.setText("hello there, you clicked me");`
按钮内的动作。如果需要在加载时在label中设置文本,可以在intialize()
@Override
public void initialize(URL location, ResourceBundle resources) {
// Set Label's text intialize() is called
label.setText("Helll There...");`
// Set Label's text on Button's action
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
label.setText("hello there, you clicked me");
}
}
}