1. public class Main extends Application {
    2. public static void main(String[] args) {
    3. launch(args);
    4. }
    5. @Override
    6. public void start(Stage primaryStage) throws Exception {
    7. Button b1 = new Button();
    8. b1.setText("这是按钮");
    9. b1.setLayoutX(100);
    10. b1.setLayoutY(50);
    11. b1.setPrefWidth(500);
    12. b1.setPrefHeight(200);
    13. // 设置按钮的字体
    14. b1.setFont(Font.font("sans-serif",40));
    15. //b1.setFont(Font.font(40));
    16. // 设置按钮的背景颜色
    17. BackgroundFill backgroundFill = new BackgroundFill(Paint.valueOf("#8FBC8F"), new CornerRadii(20), Insets.EMPTY);
    18. Background background = new Background(backgroundFill);
    19. b1.setBackground(background);
    20. // 设置按钮的边框
    21. BorderStroke borderStroke = new BorderStroke(Paint.valueOf("#8A2BE2"), BorderStrokeStyle.SOLID, new CornerRadii(20), new BorderWidths(10));
    22. Border border = new Border(borderStroke);
    23. b1.setBorder(border);
    24. // 设置按钮文字的颜色
    25. b1.setTextFill(Paint.valueOf("#CD0000"));
    26. Button b2 = new Button();
    27. b2.setText("这是按钮");
    28. b2.setLayoutX(100);
    29. b2.setLayoutY(300);
    30. b2.setPrefWidth(500);
    31. b2.setPrefHeight(200);
    32. //可以用以下的CSS样式才替代以上设置
    33. b2.setStyle(
    34. "-fx-background-color: cadetblue;"+
    35. "-fx-background-radius: 20;"+
    36. "-fx-text-fill: antiquewhite;"+
    37. "-fx-font-family: 'Microsoft YaHei UI';"+
    38. "-fx-font-size: 50"
    39. );
    40. // 按钮单击事件
    41. b2.setOnAction(new EventHandler<ActionEvent>() {
    42. @Override
    43. public void handle(ActionEvent event) {
    44. Button button = (Button)event.getSource();
    45. System.out.println(button.getText());
    46. }
    47. });
    48. //更复杂的按键监听
    49. b2.setOnMouseClicked(new EventHandler<MouseEvent>() {
    50. @Override
    51. public void handle(MouseEvent event) {
    52. if (event.getClickCount() == 2){
    53. switch (event.getButton()){
    54. case SECONDARY:
    55. System.out.println("双击右键");
    56. break;
    57. case PRIMARY:
    58. System.out.println("双击左键");
    59. break;
    60. case MIDDLE:
    61. System.out.println("双击中键");
    62. break;
    63. }
    64. }
    65. }
    66. });
    67. Group group = new Group();
    68. group.getChildren().addAll(b1,b2);
    69. Scene scene = new Scene(group);
    70. primaryStage.setScene(scene);
    71. primaryStage.setHeight(600);
    72. primaryStage.setWidth(800);
    73. primaryStage.show();
    74. primaryStage.centerOnScreen();
    75. }
    76. }