How to set preferred width and height in fxml dynamically based on screen resolution javafx

前端 未结 1 1477
旧时难觅i
旧时难觅i 2021-01-15 23:43

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

相关标签:
1条回答
  • 2021-01-16 00:38

    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.

    This looks like

    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);
        }
    }
    

    (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.)

    0 讨论(0)
提交回复
热议问题