javaFx之控件(2) 标签和按钮

package application;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;


public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {   

            BorderPane root = new BorderPane();
            ///标签

            Label label = new Label("你好");
            root.setCenter(label);


            ///按钮

            Button but = new Button("点我");
            root.setCenter(but);

            // 按钮的事件响应
            /* 方式一:匿名内部类
            but.setOnAction(new EventHandler() {

                @Override
                public void handle(ActionEvent arg0) {
                    but.setText("按钮被点击了");

                }

            });*/

            /* 方式二:Lambda表达式 */
            but.setOnAction((ActionEvent e)->{
                    but.setText("我被点击了");

            });

            // 按钮设置鼠标放进来时阴影和离开时
            DropShadow shadow = new DropShadow();
            //Adding the shadow when the mouse cursor is on
            but.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
                but.setEffect(shadow);
            });


            //Removing the shadow when the mouse cursor is off

            but.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
                but.setEffect(null);
            });

            // 与css进行交互
            but.getStyleClass().add("but");

            // 设置鼠标放上去时的提示
            but.setTooltip(new Tooltip("提示:测试"));

            /* 创建时并给按钮设置图片,放在该类相同的目录下面 */
            /*
            Image imageOk = new Image(getClass().getResourceAsStream("1.jpg"));
            Button but2 = new Button("Accept", new ImageView(imageOk));
            root.setCenter(but2);*/


            ///
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

application.css文件

/* JavaFX CSS - Leave this comment until you have at least create one rule which uses -fx-Property */

.but{
    -fx-font: 22 arial; 
    -fx-base: #b6e7c9;    
}

你可能感兴趣的:(javaFx)