JavaFX Button自適應視窗(跟著視窗大小變化)

JavaFX Button自適應視窗(跟著視窗大小變化)

在實際的應用中,經常會需要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);
}
}

實際效果如下: