ホームページ  >  記事  >  Java  >  ケーススタディ: 跳ねるボール

ケーススタディ: 跳ねるボール

王林
王林オリジナル
2024-07-16 22:12:01958ブラウズ

このセクションでは、跳ねるボールを表示し、ユーザーがボールを追加および削除できるようにするプログラムを紹介します。

セクションでは、1 つの跳ねるボールを表示するプログラムを紹介します。このセクションでは、複数の跳ねるボールを表示するプログラムを紹介します。以下の図に示すように、2 つのボタンを使用してボールの動きを一時停止および再開し、スクロール バーを使用してボールの速度を制御し、+ または - ボタンを使用してボールを追加または削除できます。

Image description

セクションの例では、ボールを 1 つだけ保存する必要がありました。この例では、複数のボールをどのように保管しますか? PanegetChildren() メソッドは、ペインにノードを保存するために、List のサブタイプである ObservableList を返します。最初はリストは空です。新しいボールが作成されたら、リストの最後に追加します。ボールを削除するには、リストの最後のボールを削除するだけです。

各ボールには、X、Y 座標、色、移動方向などの状態があります。 javafx.scene.shape.Circle を拡張する Ball という名前のクラスを定義できます。 x、y 座標と色は、Circle ですでに定義されています。ボールが作成されると、左上隅から開始して右下に移動します。新しいボールにはランダムな色が割り当てられます。

MultiplBallPane クラスはボールの表示を担当し、MultipleBounceBall クラスはコントロール コンポーネントを配置してコントロールを実装します。これらのクラスの関係を次の図に示します。以下のコードはプログラムを示します。

Image description

package application;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.util.Duration;

public class MultipleBounceBall extends Application {
    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {
        MultipleBallPane ballPane = new MultipleBallPane();
        ballPane.setStyle("-fx-border-color: yellow");

        Button btAdd = new Button("+");
        Button btSubtract = new Button("-");
        HBox hBox = new HBox(10);
        hBox.getChildren().addAll(btAdd, btSubtract);
        hBox.setAlignment(Pos.CENTER);

        // Add or remove a ball
        btAdd.setOnAction(e -> ballPane.add());
        btSubtract.setOnAction(e -> ballPane.subtract());

        // Pause and resume animation
        ballPane.setOnMousePressed(e -> ballPane.pause());
        ballPane.setOnMouseReleased(e -> ballPane.play());

        // Use a scroll bar to control animation speed
        ScrollBar sbSpeed = new ScrollBar();
        sbSpeed.setMax(20);
        sbSpeed.setValue(10);
        ballPane.rateProperty().bind(sbSpeed.valueProperty());

        BorderPane pane = new BorderPane();
        pane.setCenter(ballPane);
        pane.setTop(sbSpeed);
        pane.setBottom(hBox);

        // Create a scene and place the pane in the stage
        Scene scene = new Scene(pane, 250, 150);
        primaryStage.setTitle("MultipleBounceBall"); // 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);
    }

    private class MultipleBallPane extends Pane {
        private Timeline animation;

        public MultipleBallPane() {
            // Create an animation for moving the ball
            animation = new Timeline(new KeyFrame(Duration.millis(50), e -> moveBall()));
            animation.setCycleCount(Timeline.INDEFINITE);
            animation.play(); // Start animation
        }

        public void add() {
            Color color = new Color(Math.random(), Math.random(), Math.random(), 0.5);
            getChildren().add(new Ball(30, 30, 20, color));
        }

        public void subtract() {
            if(getChildren().size() > 0) {
                getChildren().remove(getChildren().size() - 1);
            }
        }

        public void play() {
            animation.play();
        }

        public void pause() {
            animation.pause();
        }

        public void increaseSpeed() {
            animation.setRate(animation.getRate() + 0.1);
        }

        public void decreaseSpeed() {
            animation.setRate(animation.getRate() > 0 ? animation.getRate() - 0.1 : 0);
        }

        public DoubleProperty rateProperty() {
            return animation.rateProperty();
        }

        protected void moveBall() {
            for(Node node: this.getChildren()) {
                Ball ball = (Ball)node;
                // Check boundaries
                if(ball.getCenterX() < ball.getRadius() || ball.getCenterX() > getWidth() - ball.getRadius()) {
                    ball.dx *= -1; // Change ball move direction
                }
                if(ball.getCenterY() < ball.getRadius() || ball.getCenterY() > getHeight() - ball.getRadius()) {
                    ball.dy *= -1; // Change ball move direction
                }

                // Adjust ball position
                ball.setCenterX(ball.dx + ball.getCenterX());
                ball.setCenterY(ball.dy + ball.getCenterY());
            }
        }
    }

    class Ball extends Circle {
        private double dx = 1, dy = 1;

        Ball(double x, double y, double radius, Color color) {
            super(x, y, radius);
            setFill(color); // Set ball color
        }
    }
}

add() メソッドは、ランダムな色で新しいボールを作成し、ペインに追加します (行 73)。このペインには、すべてのボールがリストに保存されます。 subtract() メソッドは、リストの最後のボールを削除します (78 行目)。

ユーザーが + ボタンをクリックすると、新しいボールがペインに追加されます (行 32)。ユーザーが - ボタンをクリックすると、配列リストの最後のボールが削除されます (行 33)。

MultipleBallPane クラスの moveBall() メソッドは、ペインのリスト内のすべてのボールを取得し、ボールの位置を調整します (行 114 ~ 115)。

以上がケーススタディ: 跳ねるボールの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:ボタン次の記事:ボタン