xml - JavaFX 获取控件问题?
黄舟
黄舟 2017-04-18 10:15:33
[Java讨论组]

用javaFX开发桌面应用遇到以下问题,
fxml里定义界面

在java程序里获取fxml定义的界面并显示

问题:我想获取fxml里定义的button控件和webview控件,查了很多资料还是没明白该怎么做?
难道JavaScript的getElementById和Android的findViewById在JavaFX里面没有嘛?

谢谢

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
PHP中文网

我写了个Demo,你看一下注释就能够明白了

FXMLDocument.fxml文件

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.*?>
<?import javafx.scene.web.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<!-- 通过fx:controller="fxml.login.FXMLExampleController绑定controller -->
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
    minWidth="-Infinity" prefHeight="210.0" prefWidth="350.0"
    xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="fxml.login.FXMLExampleController">
    <children>
        <!-- 通过fx:id绑定控件,onMouseClicked="#click"绑定事件 -->
        <Button fx:id="button" alignment="CENTER" contentDisplay="BOTTOM"
            mnemonicParsing="false" onMouseClicked="#click" text="按钮"
            textAlignment="CENTER" wrapText="true">
            <font>
                <Font size="14.0" />
            </font>
            <cursor>
                <Cursor fx:constant="DEFAULT" />
            </cursor>
        </Button>
    </children>
</VBox>

FXMLExampleController.java文件

package fxml.login;

import fxml.alert.Alert;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.stage.Stage;

public class FXMLExampleController {
    @FXML
    private Button button;// fx:id="button"

    @FXML
    protected void click() throws Exception {//onMouseClicked="#click"
        button.setText("Hahahahah");
        System.out.println("hello");

        Alert alert = new Alert();
        alert.start(new Stage());
        alert.stop();

    }
}

FXMLExample.java 启动文件

package fxml.login;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class FXMLExample  extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        //载入布局
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        Scene scene = new Scene(root);  
        primaryStage.setTitle("FXML Welcome");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    public static void main(String[] args) {
        
        launch(args);
    }

}
PHPz

在fxml中设置fx:controller,然后控件设置fx:id,然后在Controller中使用@FXML注解相应的控件对象。

类似js和Android中的方法可以使用:
Button button = (Button)parent.lookup("#myButton");

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号