如何在javafx中不断更新标签?
我正在尝试在 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 循环吗?
回答
您的代码工作正常问题仅在于您的日期对象,您还需要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 Date and Time 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));
}
}));
有关Java 8 日期和时间 Api 的更多信息
- @kleopatra I also added using the java 8 Date and Time Api