欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaFX Button自适应窗口(跟着窗口大小变化)

程序员文章站 2022-05-31 08:34:19
...

在实际的应用中,经常会需要Button或者其他的控件跟随窗口的变化而变化,下面给出Demo。

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

/**
 * Created by wzj on 2018/3/29.
 */
public class AutoSizeButton extends Application
{
    /**
     * The main entry point for all JavaFX applications.
     * The start method is called after the init method has returned,
     * and after the system is ready for the application to begin running.
     * <p>
     * <p>
     * NOTE: This method is called on the JavaFX Application Thread.
     * </p>
     *
     * @param primaryStage the primary stage for this application, onto which
     *                     the application scene can be set. The primary stage will be embedded in
     *                     the browser if the application was launched as an applet.
     *                     Applications may create other stages, if needed, but they will not be
     *                     primary stages and will not be embedded in the browser.
     */
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        Button button1 = new Button("Button1");
        Button button2 = new Button("Button2");

        button1.setMaxSize(Double.MAX_VALUE,Double.MAX_VALUE);
        button2.setMaxSize(Double.MAX_VALUE,Double.MAX_VALUE);

        Rectangle rect1 = new Rectangle(60,20);
        rect1.setFill(Color.TRANSPARENT);

        Rectangle rect2 = new Rectangle(60,20);
        rect2.setFill(Color.TRANSPARENT);

        HBox hBox = new HBox(10,rect1,button1,button2,rect2);
        hBox.setAlignment(Pos.CENTER);

        HBox.setHgrow(button1, Priority.ALWAYS);
        HBox.setHgrow(button2, Priority.ALWAYS);

        BorderPane root = new BorderPane();
        root.setBottom(hBox);

        Scene scene = new Scene(root,300,250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

实际效果如下:

JavaFX Button自适应窗口(跟着窗口大小变化)

相关标签: JavaFX Button