如何基于屏幕分辨率javafx在fxml中动态设置首选宽度和高度 [英] How to set preferred width and height in fxml dynamically based on screen resolution javafx

查看:519
本文介绍了如何基于屏幕分辨率javafx在fxml中动态设置首选宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javafx的新手.是否可以根据屏幕分辨率在fxml文件中动态设置首选的宽度和高度?我知道如何获得屏幕分辨率并将其设置为舞台:

I am new to javafx. Is it possible to dynamically set preferred width and height in an fxml file based on screen resolution? I know how to get screen resolution and set it to stage:

Screen screen = Screen.getPrimary(); 
Rectangle2D bounds = screen.getVisualBounds();
stage.setWidth(bounds.getWidth());
stage.setHeight(bounds.getHeight());

我的问题是关于在fxml文件中动态设置prefWidth和prefHeight.另外,我想知道是否可以通过编程方式更改fxml文件中的属性值,所以我正在使用场景生成器.

My question is about dynamically setting prefWidth and prefHeight in fxml files. Also I want to know if I can programmatically change property values in the fxml file, I am using scene builder.

推荐答案

您可以(以某种方式)在FXML中执行此操作,但据Scene Builder不能(据我所知).您可以使用fx:factory属性获取主屏幕,并在表达式绑定将根窗格的prefWidthprefHeight绑定到屏幕的宽度和高度.

You can (sort of) do this in FXML, but not with Scene Builder (as far as I am aware). You can use a fx:factory attribute to get the primary screen and define it in a <fx:define> block. Then use an expression binding to bind the prefWidth and prefHeight of the root pane to the width and height of the screen.

看起来像

MaximizedPane.fxml:

MaximizedPane.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Label?>
<?import javafx.stage.Screen?>

<StackPane xmlns:fx="http://javafx.com/fxml/1"
           prefWidth="${screen.visualBounds.width}" 
           prefHeight="${screen.visualBounds.height}" >
    <fx:define>
        <Screen fx:factory="getPrimary" fx:id="screen"/>
    </fx:define>
    <Label text="A maximized pane"/>    
</StackPane>

这是一个快速测试工具:

and here's a quick test harness:

import java.io.IOException;

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

public class MaximizedFXMLPane extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {
        Scene scene = new Scene(FXMLLoader.load(getClass().getResource("MaximizedPane.fxml")));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

(使用Scene Builder无法执行此操作的原因是,它不支持在FXML中插入<fx:define>块的任何机制.)

(The reason there's no way to do this with Scene Builder is that it doesn't support any mechanism for inserting <fx:define> blocks in your FXML, among other things.)

这篇关于如何基于屏幕分辨率javafx在fxml中动态设置首选宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆