如何为一个应用程序设置两个时间轴? [英] how to set up two timelines to one app?

查看:222
本文介绍了如何为一个应用程序设置两个时间轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到时间轴碰撞问题。我有一个带有动画时间轴的时钟窗格,我想添加一个带有自己时间轴的秒表。

I have a problem with timeline collision. I have working clock pane with animation timeline and I wanted to add a stopwatch with its own timeline.

因为我希望他们一起工作我现在需要改变的时候我开始秒表a不能停止它继续重启?

As I want them working together what I have to change as right now when I start stopwatch a cannot stop it as its keep restarting?

时钟应用

public class Clock extends Application {


    @Override // Override the start method in the Application class
      public void start(Stage primaryStage) {
      ClockPane clock = new ClockPane(); // Create a clock
    clock.setStyle("-fx-background-color: DARKKHAKI;");


    // Create a handler for animation
    EventHandler<ActionEvent> eventHandler = e -> {
      clock.setCurrentTime(); // Set a new clock time
    };

      // Create an animation for a running clock
      Timeline animation = new Timeline(
      new KeyFrame(Duration.millis(1000), eventHandler));
      animation.setCycleCount(Timeline.INDEFINITE);
      animation.play(); // Start animation

      // Create a scene and place it in the stage
      Scene scene = new Scene(clock, 300, 300);
      primaryStage.setTitle("Clock"); // Set the stage title
      primaryStage.setScene(scene); // Place the scene in the stage
      primaryStage.show(); // Display the stage
      primaryStage.setResizable(false);

    }

    /**
     * The main method is only needed for the IDE with limited
     * JavaFX support. Not needed for running from the command line.
     */
    public static void main(String[] args) {
      launch(args);
    }

}

时钟窗格

public class ClockPane extends Pane {


private int hour;
    private int minute;
    private int second;
    Button sButton, rButton;
    Text text;
    //Timeline timeline;
    int mins = 0, secs = 0, millis = 0;
    boolean sos = true;

    /** Construct a default clock with the current time */
    public ClockPane() {
        setCurrentTime();
    }

    /** Construct a clock with specified hour, minute, and second */
    public ClockPane(int hour, int minute, int second) {
        this.hour = hour;
        this.minute = minute;
        this.second = second;
    }

    /** Return hour */
    public int getHour() {
        return hour;
    }

    /** Set a new hour */
    public void setHour(int hour) {
        this.hour = hour;
        paintClock();
    }

    /** Return minute */
    public int getMinute() {
        return minute;
    }

    /** Set a new minute */
    public void setMinute(int minute) {
        this.minute = minute;
        paintClock();
    }

    /** Return second */
    public int getSecond() {
        return second;
    }

    /** Set a new second */
    public void setSecond(int second) {
        this.second = second;
        paintClock();
    }

    /* Set the current time for the clock */
    public void setCurrentTime() {
        // Construct a calendar for the current date and time
        Calendar calendar = new GregorianCalendar();

        // Set current hour, minute and second
        this.hour = calendar.get(Calendar.HOUR_OF_DAY);
        this.minute = calendar.get(Calendar.MINUTE);
        this.second = calendar.get(Calendar.SECOND);


        paintClock(); // Repaint the clock
    }
    void change(Text text) {
        if(millis == 1000) {
            secs++;
            millis = 0;
        }
        if(secs == 60) {
            mins++;
            secs = 0;
        }
        text.setText((((mins/10) == 0) ? "0" : "") + mins + ":"
         + (((secs/10) == 0) ? "0" : "") + secs + ":" 
            + (((millis/10) == 0) ? "00" : (((millis/100) == 0) ? "0" : "")) + millis++);
    }
    /** Paint the clock */
    private void paintClock() {



            text = new Text("00:00:000");
            text.setStyle("-fx-font-size: 11pt;-fx-stroke:silver;");
            text.setLayoutX(125);
            text.setLayoutY(180);
            Timeline timer = new Timeline(new KeyFrame(Duration.millis(1), new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    change(text);
                }
            }));
            timer.setCycleCount(Timeline.INDEFINITE);
            timer.setAutoReverse(false);
            sButton = new Button("Start");
            sButton.setLayoutX(12);
            sButton.setLayoutY(272);
            sButton.setStyle("-fx-font-size: 9pt;-fx-text-fill:#50f441;-fx-font-weight: bold;"
                    + "-fx-background-color:radial-gradient(radius 245%, black, derive(#50f441, -30%)); ");
            sButton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    if(sos) {
                        timer.play();
                        sos = false;
                        sButton.setText("Stop");
                    } else {
                        timer.pause();
                        sos = true;
                        sButton.setText("Start");
                    }
                }
            });
            rButton = new Button("Reset");
            rButton.setLayoutX(252);
            rButton.setLayoutY(272);
            rButton.setStyle("-fx-font-size: 9pt;-fx-text-fill:#50f441;-fx-font-weight: bold;"
                    + "-fx-background-color:radial-gradient(radius 245%, black, derive(#50f441, -30%)); ");
            rButton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    mins = 0;
                    secs = 0;
                    millis = 0;
                    timer.pause();
                    text.setText("00:00:000");
                    if(!sos) {
                        sos = true;
                        sButton.setText("Start");
                    }
                }
            });




        // Initialize clock parameters
        double clockRadius = Math.min(getWidth(), getHeight()) * 0.55 * 0.82;
        double centerX = getWidth() / 2;
        double centerY = getHeight() / 2;

        // Draw circle
        Circle circle = new Circle(centerX, centerY, clockRadius);


        circle.setStyle(" -fx-fill: radial-gradient(radius 245%, black, derive(GREEN, -30%)); "
                + "-fx-stroke: radial-gradient(radius 180%, darkgreen, derive(#50f441, -40%),derive(#50f441, -30%));-fx-stroke-width:10;");

        Group numbers = new Group();
        numbers.setLayoutX(142);
        numbers.setLayoutY(142);




        for(int i = 0; i < 12; i++){
            Label label = new Label(String.valueOf(i==0?12:i));
            label.setStyle("-fx-font-size: 13pt;-fx-text-fill:#50f441;-fx-font-weight: bold; ");
            Circle c=new Circle();


            c.getTransforms().add(new Rotate((i) * (360d / 12d)));
            c.getTransforms().add(new Translate(0,-100d));
            label.setTranslateX(c.localToParent(0,0).getX());
            label.setTranslateY(c.localToParent(0,0).getY());

            StackPane sp = new StackPane(c,label);
            numbers.getChildren().add(sp);
        }

        // Draw second hand
        double sLength = clockRadius * 0.65;
        double secondX = centerX + sLength * Math.sin(second * (2 * Math.PI / 60));
        double secondY = centerY - sLength * Math.cos(second * (2 * Math.PI / 60));
        Line sLine = new Line(centerX, centerY, secondX, secondY);
        sLine.setStyle(" -fx-stroke: #50f441;-fx-stroke-width: 2;-fx-stroke-line-cap: round;");

        // Draw minute hand
        double mLength = clockRadius * 0.55;
        double xMinute = centerX + mLength * Math.sin(minute * (2 * Math.PI / 60));
        double minuteY = centerY - mLength * Math.cos(minute * (2 * Math.PI / 60));
        Line mLine = new Line(centerX, centerY, xMinute, minuteY);
        mLine.setStyle(" -fx-stroke: derive(#50f441, -5%);-fx-stroke-width: 4;-fx-stroke-line-cap: round;");

        // Draw hour hand
        double hLength = clockRadius * 0.35;
        double hourX = centerX + hLength * Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));
        double hourY = centerY - hLength * Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));
        Line hLine = new Line(centerX, centerY, hourX, hourY);

        hLine.setStyle(" -fx-stroke: derive(#50f441, -30%);-fx-stroke-width: 6;-fx-stroke-line-cap: round;");


        getChildren().clear();
        getChildren().addAll(circle, sLine, mLine, hLine, numbers,sButton,rButton,text);
    }

    @Override
    public void setWidth(double width) {
        super.setWidth(width);
        paintClock();
    }

    @Override
    public void setHeight(double height) {
        super.setHeight(height);
        paintClock();
    }

}


推荐答案

我使用James的想法创建了一个版本。

I create a version using James' ideas.


Main:

Main:



import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication200 extends Application
{

    @Override // Override the start method in the Application class
    public void start(Stage primaryStage)
    {

        FakeCustomNode clockNode = new FakeCustomNode();

        Scene scene = new Scene(clockNode, 300, 300);
        primaryStage.setTitle("Clock"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
        primaryStage.setResizable(false);

    }

    /**
     * The main method is only needed for the IDE with limited JavaFX support.
     * Not needed for running from the command line.
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}




FakeCustomNodeClass

FakeCustomNodeClass



import javafx.scene.layout.VBox;

/**
 *
 * @author blj0011
 */
final public class FakeCustomNode extends VBox
{

    ClockGUI clock;
    StopWatchGUI stopWatchGUI;

    public FakeCustomNode()
    {
        clock = new ClockGUI();
        stopWatchGUI = new StopWatchGUI();

        getChildren().addAll(clock.getCurrentClock(), stopWatchGUI.getStopWatch());
    }

}




StopWAtchGUI类:

StopWAtchGUI Class:



import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.Duration;

/**
 *
 * @author blj0011
 */
public class StopWatchGUI
{
    Text display;
    Button start;
    Button pause;
    Button reset;
    VBox vbox = new VBox();

    int second = 0;

    public StopWatchGUI()
    {
        display = new Text("00:00:00");
        start = new Button("Start");
        pause = new Button("Pause");
        reset = new Button("Reset");

        Timeline stopWatchTimeline = new Timeline(new KeyFrame(Duration.seconds(1), (ActionEvent event) -> {
            second++;
            display.setText(String.format("%02d:%02d:%02d", second / 3600, (second % 3600) / 60, second % 60));
        }));
        stopWatchTimeline.setCycleCount(Timeline.INDEFINITE);
        stopWatchTimeline.play();

        start.setOnAction((event) -> {
            stopWatchTimeline.play();
        });
        pause.setOnAction((event) -> {
            stopWatchTimeline.pause();
        });
        reset.setOnAction((event) -> {
            stopWatchTimeline.stop();
            second = 0;
            display.setText("00:00:00");
        });
        vbox.getChildren().addAll(display, new HBox(start, pause, reset));
    }

    public VBox getStopWatch()
    {
        return vbox;
    }

}




ClockGUI类:

ClockGUI Class:



import java.time.LocalDateTime;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.transform.*;
import javafx.util.Duration;

/**
 *
 * @author Sedrick
 */
public class ClockGUI
{

    Circle clockFace;
    Line second;
    Line minute;
    Line hour;
    Rotate secondRotation;
    Rotate minuteRotation;
    Rotate hourRotation;
    AnchorPane currentClockFace;

    LocalDateTime localDateTime;

    public ClockGUI()
    {
        currentClockFace = new AnchorPane();
        currentClockFace.setPrefSize(100, 100);

        clockFace = new Circle(100 / 2, 100 / 2, 100 / 2);
        clockFace.setStroke(Color.BLACK);
        clockFace.setFill(Color.TRANSPARENT);

        second = new Line(100 / 2, 100 / 2, 100 / 2, 100 / 2 - 40);
        secondRotation = new Rotate();
        secondRotation.pivotXProperty().bind(second.startXProperty());
        secondRotation.pivotYProperty().bind(second.startYProperty());
        second.getTransforms().add(secondRotation);

        minute = new Line(100 / 2, 100 / 2, 100 / 2, 100 / 2 - 30);
        minuteRotation = new Rotate();
        minuteRotation.pivotXProperty().bind(minute.startXProperty());
        minuteRotation.pivotYProperty().bind(minute.startYProperty());
        minute.getTransforms().add(minuteRotation);

        hour = new Line(100 / 2, 100 / 2, 100 / 2, 100 / 2 - 20);
        hourRotation = new Rotate();
        hourRotation.pivotXProperty().bind(hour.startXProperty());
        hourRotation.pivotYProperty().bind(hour.startYProperty());
        hour.getTransforms().add(hourRotation);

        currentClockFace.getChildren().addAll(clockFace, second, minute, hour);

        setToCurrentTime();
        Timeline clockTimeline = new Timeline(new KeyFrame(Duration.seconds(1), (ActionEvent event) -> {
            setToCurrentTime();
        }));
        clockTimeline.setCycleCount(Timeline.INDEFINITE);
        clockTimeline.play();

    }

    public AnchorPane getCurrentClock()
    {
        return currentClockFace;
    }

    public void setRotateSecond(double degree)
    {
        secondRotation.setAngle(degree);
    }

    public void setRotateMinute(double degree)
    {
        minuteRotation.setAngle(degree);
    }

    public void setRotateHour(double degree)
    {
        hourRotation.setAngle(degree);
    }

    private void setToCurrentTime()
    {
        localDateTime = LocalDateTime.now();
        setRotateSecond(localDateTime.getSecond() * 6);
        setRotateMinute(localDateTime.getMinute() * 6);
        setRotateHour(((localDateTime.getHour() % 12) * 6) + (localDateTime.getMinute() * .1));
        System.out.println(localDateTime.getSecond() * 6);
        System.out.println(localDateTime.getMinute() * 6);
        System.out.println(((localDateTime.getHour() % 12) * 6) + (localDateTime.getMinute() * .1));
    }
}

这是快速完成的。代码可能存在问题!

这篇关于如何为一个应用程序设置两个时间轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆