package fx.com;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.*;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Button b2 = new Button();
b2.setText("这是按钮");
b2.setLayoutX(100);
b2.setLayoutY(300);
b2.setPrefWidth(500);
b2.setPrefHeight(200);
b2.setStyle(
"-fx-background-color: cadetblue;" +
"-fx-background-radius: 20;" +
"-fx-text-fill: antiquewhite;" +
"-fx-font-family: 'Microsoft YaHei UI';" +
"-fx-font-size: 50"
);
// 按钮单击事件
b2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Button button = (Button) event.getSource();
System.out.println(button.getText());
}
});
// 响应鼠标的另一种形式
b2.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
System.out.println(event.getButton().name());
//System.out.println("鼠标单击");
if (event.getClickCount() == 2 && event.getButton().name().equals(MouseButton.PRIMARY.name())) {
System.out.println("鼠标双击");
}
});
Group group = new Group();
group.getChildren().addAll(b2);
Scene scene = new Scene(group);
// 第一种
KeyCombination kc1 = new KeyCodeCombination(KeyCode.C, KeyCombination.ALT_DOWN, KeyCombination.CONTROL_DOWN);
Mnemonic mnemonic1 = new Mnemonic(b2, kc1);
scene.addMnemonic(mnemonic1);
// 第二种
KeyCombination kc2 = new KeyCharacterCombination("O", KeyCombination.ALT_DOWN);
Mnemonic mnemonic2 = new Mnemonic(b2, kc2);
scene.addMnemonic(mnemonic2);
// 第三种
KeyCodeCombination kc4 = new KeyCodeCombination(KeyCode.Y, KeyCombination.SHORTCUT_DOWN);
scene.getAccelerators().put(kc4, new Runnable() {
@Override
public void run() {
System.out.println("run()方法");
b2.fire();
}
});
primaryStage.setScene(scene);
primaryStage.setHeight(600);
primaryStage.setWidth(800);
primaryStage.show();
primaryStage.centerOnScreen();
}
}