JavaFX 之自定義窗口標題欄(二)


一、問題場景

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

效果演示圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM