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