当用户单击按钮时,JavaFX Button类可以触发事件。Button类扩展了Labeled类,可以显示文本,图像或两者都可以。
以下代码显示了如何向Button添加单击操作侦听器。
-
import javafx.application.Application;
-
import javafx.event.ActionEvent;
-
import javafx.event.EventHandler;
-
import javafx.scene.Scene;
-
import javafx.scene.control.Button;
-
import javafx.scene.layout.StackPane;
-
import javafx.stage.Stage;
-
public class Main extends Application {
-
public static void main(String[] args) {
-
launch(args);
-
}
-
@Override
-
public void start(Stage primaryStage) {
-
primaryStage.setTitle("Hello World!");
-
Button btn = new Button();
-
btn.setText("Say 'Hello World'");
-
btn.setOnAction(new EventHandler<ActionEvent>() {
-
@Override
-
public void handle(ActionEvent event) {
-
System.out.println("Hello World!");
-
}
-
});
-
StackPane root = new StackPane();
-
root.getChildren().add(btn);
-
primaryStage.setScene(new Scene(root, 300, 250));
-
primaryStage.show();
-
}
-
}
创建按钮
我们使用以下构造函数在JavaFX中创建一个Button。
创建带有空文本标题的按钮。
Button button = new Button();
创建具有指定文本的按钮。
Button button = new Button("OK");
按钮操作
我们可以使用Button类的setOnAction方法为用户单击事件添加点击事件处理程序。
-
button.setOnAction((ActionEvent e) -> {
-
System.out.println("clicked");
-
});
按钮鼠标事件
以下代码显示了如何处理Button的Mouse in和Mouse out(鼠标移入和移出)事件。
-
import javafx.application.Application;
-
import javafx.event.EventHandler;
-
import javafx.scene.Group;
-
import javafx.scene.Scene;
-
import javafx.scene.control.Button;
-
import javafx.scene.input.MouseEvent;
-
import javafx.scene.layout.VBox;
-
import javafx.stage.Stage;
-
public class Main extends Application {
-
public static void main(String[] args) {
-
launch(args);
-
}
-
@Override
-
public void start(Stage stage) {
-
Group group = new Group();
-
Scene scene = new Scene(group);
-
stage.setWidth(300);
-
stage.setHeight(190);
-
VBox vbox = new VBox();
-
vbox.setLayoutX(20);
-
vbox.setLayoutY(20);
-
final Button button1 = new Button("OK");
-
button1.addEventHandler(MouseEvent.MOUSE_ENTERED,(e)->System.out.println("mouse entered"));
-
button1.addEventHandler(MouseEvent.MOUSE_EXITED,(e)->System.out.println("mouse out"));
-
vbox.getChildren().add(button1);
-
vbox.setSpacing(10);
-
group.getChildren().add(vbox);
-
stage.setScene(scene);
-
stage.show();
-
}
-
}
文