一、問題場景
PC客戶端登錄界面仿QQ,上邊顯示圖片,下邊顯示輸入框和登錄按鈕。而JavaFX默認的窗口,不滿足需求。
二、解決思路
隱藏窗口默認的標題欄,使用創建label對象,使用css將按鈕圖片替換到label對象中進行布局,充當按鈕。
三、代碼實現
Java 代碼,代碼舉例自定義標題欄樣式。
/** * 程序入口 * @author Light */ public class JavaFXTest extends Application { @Override public void start(Stage stage) { stage.initStyle(StageStyle.TRANSPARENT); VBox root = new VBox(); root.setId("root"); // 引入樣式 root.getStylesheets().add(JavaFXTest.class.getResource("/resources/style.css").toString()); //頂部 VBox top = new VBox(); top.setId("top"); top.setPrefSize(300,26); // 標題欄 AnchorPane title = new AnchorPane(); Label close = new Label(); close.setPrefWidth(33); close.setPrefHeight(26); close.setId("winClose");//winClose css樣式Id title.getChildren().add(close); AnchorPane.setRightAnchor(close, 0.0); AnchorPane.setTopAnchor(close, 5.0); top.getChildren().add(title); // 內容 VBox content = new VBox(); content.setPrefWidth(300); content.setMinHeight(200); // 組裝 root.getChildren().addAll(top, content); Scene scene = new Scene(root); stage.setScene(scene); // 顯示 stage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
css 代碼:
#root { -fx-border-width:2;-fx-border-color:#000; } #top { -fx-background-color: #4A5459; } #winClose { -fx-cursor:hand; } #winClose{ -fx-background-image:url("/resources/winClose_0.png"); -fx-background-repeat:no-repeat; } #winClose:hover { -fx-background-image:url("/resources/winClose_1.png"); } #winClose:pressed { -fx-background-image:url("/resources/winClose_2.png"); }
效果演示圖: