首页  >  文章  >  Java  >  按钮

按钮

PHPz
PHPz原创
2024-07-16 22:02:101195浏览

按钮是一个点击时触发动作事件的控件。 JavaFX 提供常规按钮、切换按钮、复选框按钮和单选按钮。这些按钮的共同特征定义在 ButtonBaseLabeled 类中,如下图所示。

Image description

Labeled 类定义标签和按钮的通用属性。按钮就像标签一样,只不过按钮具有 ButtonBase 类中定义的 onAction 属性,该属性设置用于处理按钮操作的处理程序。

下面的代码给出了一个使用按钮来控制文本移动的程序,如下图所示。

package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;

public class ButtonDemo extends Application {
    protected Text text = new Text(50, 50, "JavaFX Programming");

    protected BorderPane getPane() {
        HBox paneForButtons = new HBox(20);
        Button btLeft = new Button("Left", new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/lo.jpg"));
        Button btRight = new Button("Right", new ImageView("file:/C:/Users/Paul/development/MyJavaFX/src/application/image/lo.jpg"));
        paneForButtons.getChildren().addAll(btLeft, btRight);
        paneForButtons.setAlignment(Pos.CENTER);
        paneForButtons.setStyle("-fx-border-color: green");

        BorderPane pane = new BorderPane();
        pane.setBottom(paneForButtons);

        Pane paneForText = new Pane();
        paneForText.getChildren().add(text);
        pane.setCenter(paneForText);

        btLeft.setOnAction(e -> text.setX(text.getX() - 10));
        btRight.setOnAction(e -> text.setX(text.getX() + 10));

        return pane;
    }

    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {
        // Create a scene and place it in the stage
        Scene scene = new Scene(getPane(), 450, 200);
        primaryStage.setTitle("ButtonDemo"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
    }

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

Image description

程序创建两个按钮 btLeftbtRight,每个按钮包含一个文本和一个图像(第 18-19 行)。这些按钮放置在 HBox 中(第 20 行),而 HBox 放置在边框窗格的底部(第 25 行)。文本在第 14 行中创建,并放置在边框窗格的中心(第 29 行)。 btLeft 的操作处理程序将文本移动到左侧(第 31 行)。 btRight 的操作处理程序将文本移动到右侧(第 32 行)。

程序特意定义了一个受保护的 getPane() 方法来返回一个窗格(第 16 行)。在接下来的示例中,该方法将被子类覆盖,以在窗格中添加更多节点。该文本被声明为受保护的,以便子类可以访问它(第 14 行)。

以上是按钮的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn