java—如何在javafx中不断更新标签?

cyej8jka  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(388)

我试图在javafx中每秒更新一个标签的文本。有没有像swing中那样的repaint()方法可以让我在javafx中实现这一点。我试图让我的应用程序显示时间和更新标签与新的当前时间每秒。
谢谢您!我的代码在下面。

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import javax.management.timer.Timer;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.stage.Stage;
import javafx.util.Duration;
public class TimeAppGraphics extends Application
{
    private static final String Indefinite = null;
    public static void main(String[] args)
    {
        // start app by launching software
        launch(args);
    }
    @Override // overides the parent class
    public void start(Stage myStage)
    {
        Button exitButton = new Button("Exit!"); // creates an exit button for the app.
        myStage.setTitle("Bell Application"); //sets the title of the application to Bell app
        exitButton.setFont(Font.font("Impact" ,FontPosture.ITALIC,  24)); //sets the font for the button
        exitButton.setLayoutX(215);
        exitButton.setLayoutY(370);
        //This method create the event for the button, to close the application.
        exitButton.setOnAction(ae -> {
            // TODO Auto-generated method stub
            try
            {
                Platform.exit(); //exits app.
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage()); //prints error if there is one.
            }
        });
        //Now to add an Image to the stage
        myStage.setHeight(500); // sets the panel to be 500 by 500  pixels.
        myStage.setWidth(500);

        LocalTime time = LocalTime.now();

        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();

        FlowPane fp = new FlowPane();
        DateFormat timeFormat = new SimpleDateFormat( "HH:mm" );

        Label timeLabel = new Label();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

        final int millis = 50;
        Timer tmr = new Timer();
        tmr.start();
        boolean bool = true;

        timeLabel.setTextFill(Color.LAWNGREEN);
        timeLabel.setFont(new Font("Impact", 24));
        timeLabel.setLayoutX(0);
        timeLabel.setLayoutY(100);
        //Period Label
        Calendar calender = Calendar.getInstance();
        Label periodLabel = new Label();
        int weekNum = calender.get(Calendar.WEEK_OF_YEAR);
        if(weekNum % 2 != 0)
        {
            int dayNum = calender.get(Calendar.DAY_OF_WEEK);
            switch(dayNum)
            {
            case 2:
                String dayType = "A Day";
                if(hour >= 7 && minute >= 35 && hour <= 9 && minute <= 11)
                {
                    String period = "A Period";
                    periodLabel.setText(period);
                }
            }
        }
        try
        {
            //For the image
            //_______________________________________________________________________________________________
            //this try catch catches  errors for the file.
            Image bell = new Image("https://media.istockphoto.com/vectors/school-bell-vector-id526811999?k=6&m=526811999&s=612x612&w=0&h=7XrnFiPTYW5aBjHQwPL5eGpK01ZFKs61q6N2yks60Wg=");
            ImageView bellDisplay = new ImageView(bell); // sets a new imageview, which paints the image to the screen.
            bellDisplay.setX(175); //positions the x axis of the image
            bellDisplay.setY(175); // positions the image on the y axis
            //set fit
            bellDisplay.setFitHeight(150);
            bellDisplay.setFitWidth(150);
            //set preseve ratio
            bellDisplay.setPreserveRatio(true);
            //______________________________________________________________________________________________

            Date date = new Date();
            time = LocalTime.now();
            hour = time.getHour();
            minute = time.getMinute();
            second = time.getSecond();
            Timeline timeline = new Timeline(

                    new KeyFrame(Duration.seconds(1),
                            actionEvent -> timeLabel.setText("Time: " + simpleDateFormat.format(date))
                            ));
            timeline.getKeyFrames();
            //fp.getChildren().add(timeLabel);
            timeline.setCycleCount(Animation.INDEFINITE);//Repeat this 100 times

            timeline.play();
            //fp.getChildren().add(exitButton);
            //fp.getChildren().add(bellDisplay);
            Group objects = new Group(exitButton, bellDisplay, timeLabel); //groups the objects together to be shown.
            Scene scene = new Scene(objects, 1000,1000 , Color.ROYALBLUE); // creates a scene to be displayed.
            myStage.setScene(scene); //creates the program
        }

        catch(Exception e)
        {
            System.out.println(e.getMessage()); // prints error
        }
        myStage.show();
    }
}

您将如何持续更新标签?你能用while循环更新文本吗?

ct2axkht

ct2axkht1#

你的代码工作正常问题只是你的日期对象,你还需要得到新的 DateAndTime 将新值设置为 timeLabel :

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
    public void handle(ActionEvent actionEvent) {
        Date date = new Date();
        timeLabel.setText("Time: " + simpleDateFormat.format(date));
    }
}));

使用java 8日期和时间api的更好方法是:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
    public void handle(ActionEvent actionEvent) {
        LocalDateTime date = LocalDateTime.now();
        timeLabel.setText("Time: " + formatter.format(date));
    }
}));

关于Java8日期和时间api的更多信息

相关问题