gpt4 book ai didi

Java 刷新的日期

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:45 25 4
gpt4 key购买 nike

我想在 JFrame 中显示 java.util.Date,并且始终刷新以查看新日期。

package pro;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.Timer;

public class Date {

public static Timer t;


public static void main(String [] args){

time();

}
public static Timer time(){

t = new Timer(1000, new ActionListener(){

@SuppressWarnings("deprecation")

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(null, new java.util.Date().toGMTString());

}

});

t.setRepeats(true);

t.start();

return t;
}
}

我想我在计时器方法中犯了一些错误

我也尝试过编辑它

package pro;

import java.awt.FlowLayout;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class date {

private static JLabel l;
private static Date d = new Date();
private static JFrame f;

@SuppressWarnings("deprecation")

public static void main(String [] args){

f = new JFrame("Date program");

f.setVisible(true);
f.pack();
f.revalidate();
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

l = new JLabel(d.toGMTString());


f.add(l);
while(true){

l.revalidate();

}
}

}

任何回复将不胜感激。

最佳答案

"when I just write it like this it gets the date in the second I run it without being changed."

只需将 JLabel 添加到 JOPtionPane 中,并仅更新 Timer 中的 JLabel。不要将 JOptionPane 放在 Timer 代码中。这是一个例子

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Clock {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
final Date date = new Date();
final JLabel timeLabel = new JLabel(date.toString());
Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
date.setTime(System.currentTimeMillis());
timeLabel.setText(date.toString());
}
});
timer.start();
JOptionPane.showMessageDialog(null, timeLabel);
}
});
}
}

关于Java 刷新的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21859981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com