这是我的示例 GUI 草稿,我只是想创建一个具有今天相应日期和日期的面板,以更改今天日程安排的内容。
是否可以创建一个带有“今天”和“日期”标签的面板,根据今天的日期和今天的数据来更改内容?
最佳答案
这是一个简单的示例 JFrame
,其中的标签显示今天的日期:
public class FrameWithTodaysDate extends JFrame {
JLabel todayLabel = new JLabel();
public FrameWithTodaysDate() {
super("Day Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTodaysDate();
add(todayLabel);
pack();
}
private void setTodaysDate() {
String today = LocalDate.now(ZoneId.of("Asia/Tokyo"))
.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL));
todayLabel.setText(today);
}
public static void main(String[] args) {
new FrameWithTodaysDate().setVisible(true);
}
}
今天在我的电脑上它看起来像:
请填写您想要的时区,我把亚洲/东京放在其中。
如果您需要在新的一天开始时(午夜)更新框架中的日期,请按照 Sergiy Medvynskyy 在 a comment 中建议的那样使用计时器。 。我正在重写setTodaysDate
:
private void setTodaysDate() {
ZonedDateTime now = ZonedDateTime.now(zone);
LocalDate today = now.toLocalDate();
String todayString = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL));
todayLabel.setText(todayString);
int millisUntilTomorrow = (int) ChronoUnit.MILLIS.between(now,
today.plusDays(1).atStartOfDay(zone));
Timer nextUpdate = new Timer(millisUntilTomorrow, e -> setTodaysDate());
nextUpdate.setRepeats(false);
nextUpdate.start();
}
它可能看起来有点复杂,因为我考虑了夏令时 (DST) 等因素:一天可能是 23 或 25 小时,并且可能不是从 00:00 开始。
为了让方法发挥作用,我们需要
private ZoneId zone = ZoneId.of("Asia/Tokyo");
应该是这样。
关于java - 创建一个带有今天日期标签的面板,根据今天的数据更改内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49941143/