📜  javafx UI按钮(1)

📅  最后修改于: 2023-12-03 15:31:35.780000             🧑  作者: Mango

JavaFX UI Buttons

JavaFX provides a set of user interface (UI) controls, including buttons, that can be easily customized and styled to fit the look-and-feel of any application. In this guide, we will focus specifically on JavaFX UI buttons.

Creating a JavaFX Button

Creating a JavaFX button is simple. Here is an example:

Button button = new Button("Click me!");

This will create a basic button with the text "Click me!". You can add the button to a JavaFX layout, such as a VBox or HBox, using the getChildren() method:

VBox vbox = new VBox();
vbox.getChildren().add(button);
Styling a JavaFX Button

JavaFX buttons can be styled using Cascading Style Sheets (CSS). You can create a new CSS file, and add the following code to it:

.button {
  -fx-background-color: #1E90FF;
  -fx-text-fill: white;
  -fx-font-size: 16px;
  -fx-font-weight: bold;
  -fx-padding: 10px 20px;
  -fx-border-radius: 5px;
}

This will style all JavaFX buttons with a blue background, white text, bold 16px font, and rounded corners. To apply this style to a particular button, you can add a CSS class:

button.getStyleClass().add("button");
Responding to Button Clicks

To respond to a button click, you can add an event handler:

button.setOnAction(new EventHandler<ActionEvent>() {
  @Override
  public void handle(ActionEvent event) {
    // code to be executed on button click
  }
});

Alternatively, you can use a lambda expression:

button.setOnAction(event -> {
  // code to be executed on button click
});
Conclusion

JavaFX provides a powerful set of UI controls, including buttons, that can be easily customized and styled to fit any application. With a few lines of code, you can create a fully functional button and respond to user input.