Java图形用户界面:JavaFx

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import java.io.IOException;
import java.net.URL;

public class javaFxDemo extends Application {

	@Override
    public void start(Stage primaryStage) throws IOException {

		// 设置窗口标题
        primaryStage.setTitle("JavaFX Demo");
        
        // 创建一个标签
        Label label = new Label("Hello, JavaFX!");
        
        label.setFont(Font.font("Arial", FontWeight.BOLD, 24));

        // 创建一个按钮
        Button button = new Button("Click Me!");
        
        // 为按钮添加点击事件处理器
        button.setOnAction(event -> label.setText("Button Clicked!"));
        
        	 
	 	// 创建根节点
        //StackPane root = new StackPane();
        //VBox root = new VBox();
        HBox root = new HBox();
        
        // 将Button添加到StackPane中
        root.getChildren().add(label);
        root.getChildren().add(button);
        
        // 加载CSS文件并添加到样式表中
        // 注意这里使用的是getResource,不是getResourceAsStream
        URL cssUrl = getClass().getResource("/styles.css"); 
        if (cssUrl != null) {
        	// 使用toExternalForm()获取URL的字符串表示
        	root.getStylesheets().add(cssUrl.toExternalForm()); 
        } else {
            System.err.println("CSS file not found!");
        }
        
        // 为根节点设置样式类
        root.getStyleClass().add("background-pane");
        
        // 创建场景并设置根节点
        Scene scene = new Scene(root, 800, 600);
        
        // 设置舞台
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

styles.css

/* styles.css */

.background-pane {
    -fx-background-image: url("file:src/main/resources/background.jpg"); /* 替换为你的图片路径 */
    -fx-background-repeat: no-repeat;
    -fx-background-size: cover; /* 或者使用其他尺寸选项,如 "contain", "auto" 等 */
    -fx-background-position: center;
    -fx-padding: 20px; /* 可选,为节点添加内边距 */
}


.root {
    -fx-background-color: #f0f0f0;
}

.button {
    -fx-background-color: #4CAF50;
    -fx-text-fill: white;
    -fx-font-size: 16px;
    -fx-padding: 10px;
    -fx-border-radius: 5px;
    -fx-background-radius: 5px;
    -fx-cursor: hand;
}

.button:hover {
    -fx-background-color: #45a049;
}

.label {
    -fx-text-fill: #333333;
    -fx-font-size: 36px;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值