首頁  >  文章  >  Java  >  按鈕

按鈕

PHPz
PHPz原創
2024-07-16 22:02:101197瀏覽

按鈕是一個點擊時觸發動作事件的控制項。 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