JavaFX Scene Builder中Label点击按钮不显示内容问题求助
你遇到的问题由三处配置缺失导致,按以下步骤修改即可正常运行:
- 第一处:
TesterController.java中的printsHelloWorld方法未添加@FXML注解,FXML无法识别非公开的方法作为事件回调入口 - 第二处:
Tester.fxml中的Label标签未声明fx:id="l1",无法和Controller中@FXML注入的l1对象完成绑定 - 第三处:
Tester.fxml中的Button标签未绑定onAction="#printsHelloWorld"事件,点击按钮无法触发Controller中的对应方法
修改后的TesterController.java代码
package helloworld; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; public class TesterController implements Initializable { @FXML private Label l1; // 新增@FXML注解 @FXML void printsHelloWorld(ActionEvent event){ l1.setText("Hello World"); } @Override public void initialize(URL url, ResourceBundle rb) { // 此处可保留空实现 } }
修改后的Tester.fxml代码
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.Label?> <?import javafx.scene.layout.AnchorPane?> <AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.171" fx:controller="helloworld.TesterController"> <children> <!-- 新增onAction事件绑定 --> <Button layoutX="201.0" layoutY="155.0" mnemonicParsing="false" prefHeight="161.0" prefWidth="175.0" text="Button" onAction="#printsHelloWorld" /> <!-- 新增fx:id和Controller的l1绑定 --> <Label fx:id="l1" layoutX="170.0" layoutY="59.0" prefHeight="46.0" prefWidth="237.0" /> </children> </AnchorPane>
运行日志中的版本警告不影响功能,属于FXML编译版本和运行时JDK版本的小差异,在JavaFX 8大版本范围内完全兼容,无需额外处理。
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

