xml - JavaFX 获取控件问题?
本文介绍了xml - JavaFX 获取控件问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
用javaFX开发桌面应用遇到以下问题,
fxml里定义界面
在java程序里获取fxml定义的界面并显示
问题:我想获取fxml里定义的button控件和webview控件,查了很多资料还是没明白该怎么做?
难道JavaScript的getElementById和Android的findViewById在JavaFX里面没有嘛?
谢谢
解决方案
我写了个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);
}
}
这篇关于xml - JavaFX 获取控件问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文