我正在尝试使用 eclipse 和场景生成器制作一个“Hello World”。
package lj.HelloWorld;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
public class HelloWorld extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
initRootLayout();
}
/**
* Initializes the root layout.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(HelloWorld.class.getResource("rootHelloWorld.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
// my attempt to refer to my label object in scenebuilder.
@FXML
private Label lblOutput;
@FXML
private void handleClick(ActionEvent event) {
lblOutput.setText("This");
}
}
这是我的 fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane prefHeight="200.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<center>
<Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<children>
<Button fx:id="btnClick" layoutX="98.0" layoutY="14.0" mnemonicParsing="false" text="Click Me" />
<Label fx:id="lblOutput" layoutX="167.0" layoutY="18.0" text="1231231" />
</children>
</Pane>
</center>
</BorderPane>
我只是想知道如何引用标签并将其文本更改为“Hello World”。 PS:我来自vb.net,学习java。我尝试在谷歌上寻找 Hello World 示例,但有些网站已关闭,而其他网站对我来说太复杂了。就像 ch.makery 教程一样。
最佳答案
您需要一个 Controller 类
package lj.HelloWorld;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.text.Text;
public class FXMLDocumentController {
@FXML private Label lblOutput;
@FXML protected void handleButtonAction(ActionEvent e){
lblOutput.setText("Hello World");
}
}
并告诉您的 XML Controller 类
<BorderPane fx:controller="lj.HelloWorld.FXMLDocumentController"
<Button fx:id="btnClick" layoutX="98.0" layoutY="14.0" mnemonicParsing="false" text="Click Me"
onAction="#handleButtonAction"/>
有关详细信息和教程,请阅读:http://docs.oracle.com/javafx/2/get_started/hello_world.htm
关于java - 如何使用 Eclipse 和场景生成器更改 Java 中的标签文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27499450/