级联样式表,也称为CSS,是一种简单的设计语言,旨在简化使网页呈现的过程.
CSS处理外观和感觉是网页的一部分.使用CSS,您可以控制文本的颜色,字体的样式,段落之间的间距,列的大小和布局.除此之外,您还可以控制使用的背景图像或颜色,布局设计,不同设备和屏幕尺寸的显示变化以及各种其他效果.
JavaFX为您提供了使用CSS来增强应用程序外观的功能.包 javafx.css 包含用于为JavaFX应用程序应用CSS的类.
CSS包含由浏览器解释的样式规则然后应用于文档中的相应元素.
样式规则由三部分组成,即 :
选择器 : 选择器是将应用样式的HTML标记.这可以是< h1> 或< table> 等任何标签.
财产 : 属性是HTML标记的一种属性.简单来说,所有HTML属性都转换为CSS属性.它们可以是颜色,边框等.
值 : 值将分配给属性.例如,颜色属性可以具有红色或#F1F1F1 等值.
您可以将CSS样式规则语法设置如下 :
selector {property:value}
JavaFX使用的默认样式表是 modena.css .它位于JavaFX运行时jar中.
您可以将自己的样式表添加到JavaFX中的场景,如下所示 :
Scene scene = new Scene(new Group(), 500, 400); scene.getStylesheets().add("path/stylesheet.css");
您还可以使用 setStyle()
.button { -fx-background-color: red; -fx-text-fill: white; }
假设我们开发了一个显示带有Text的表单的JavaFX应用程序字段,密码字段,两个按钮.默认情况下,此表单看起来如下面的屏幕截图所示;
以下程序演示了如何在JavaFX中向上述应用程序添加样式.
将此代码保存在名为 CssExample.java
import javafx.application.Application; import static javafx.application.Application.launch; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.stage.Stage; public class CssExample extends Application { @Override public void start(Stage stage) { //creating label email Text text1 = new Text("Email"); //creating label password Text text2 = new Text("Password"); //Creating Text Filed for email TextField textField1 = new TextField(); //Creating Text Filed for password PasswordField textField2 = new PasswordField(); //Creating Buttons Button button1 = new Button("Submit"); Button button2 = new Button("Clear"); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Setting size for the pane gridPane.setMinSize(400, 200); //Setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the vertical and horizontal gaps between the columns gridPane.setVgap(5); gridPane.setHgap(5); //Setting the Grid alignment gridPane.setAlignment(Pos.CENTER); //Arranging all the nodes in the grid gridPane.add(text1, 0, 0); gridPane.add(textField1, 1, 0); gridPane.add(text2, 0, 1); gridPane.add(textField2, 1, 1); gridPane.add(button1, 0, 2); gridPane.add(button2, 1, 2); //Styling nodes button1.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;"); button2.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;"); text1.setStyle("-fx-font: normal bold 20px 'serif' "); text2.setStyle("-fx-font: normal bold 20px 'serif' "); gridPane.setStyle("-fx-background-color: BEIGE;"); // Creating a scene object Scene scene = new Scene(gridPane); // Setting title to the Stage stage.setTitle("CSS Example"); // Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } }
使用以下命令从命令提示符编译并执行保存的java文件.
javac CssExample.java java CssExample
执行时,上述程序生成一个JavaFX窗口,如下所示.