如何JAVA应用程序中显示当前时间
发布网友
发布时间:2022-04-24 00:49
我来回答
共2个回答
热心网友
时间:2022-06-18 21:27
//测试通过
//你把具体的异常贴出来
import javax.swing.*;
import java.awt.event.*;
import java.text.*;
import java.awt.*;
import java.util.Date;;
public class Main
{
public static void main(String[] args)
{
new TimeFrame("系统时间");
}
}
class TimeFrame extends JFrame
{
public TimeFrame(final String title)
{
setTitle(title);
setSize(300,150);
setLocation(300, 200);
JPanel panel = new JPanel();
ltime.setFont(new Font("仿宋",Font.PLAIN,30));
panel.add(ltime,BorderLayout.CENTER);
add(panel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Timer timer = new Timer(1000,new
ActionListener()
{
DateFormat format = DateFormat.getTimeInstance(DateFormat.MEDIUM);
public void actionPerformed(ActionEvent event)
{
ltime.setText(format.format(new Date(System.currentTimeMillis())));
}
});
timer.start();
}
private final JLabel ltime = new JLabel();
}
热心网友
时间:2022-06-18 21:28
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.Timer;
public class JTest
{
public static void main(String args[])
{
JFrame frame=new JFrame("Test");
MyPanel panel=new MyPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
class MyPanel extends JPanel
{
private Run r=new Run();
private JLabel label=new JLabel();
class Listner implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
MyPanel()
{
super();
add(label);
Listner listener=new Listner();
Timer t=new Timer(1000,listener);//每隔1000毫秒重复
t.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
r=new Run();
GregorianCalendar now=r.getDate();
int hours =now.get(Calendar.HOUR);
int minutes=now.get(Calendar.MINUTE);
int seconds=now.get(Calendar.SECOND);
label.setText(hours+":"+minutes+":"+seconds);
}
}
class Run implements Runnable
{
private GregorianCalendar now=new GregorianCalendar();;
public GregorianCalendar getDate()//返回当前时间
{
return now;
}
public void setClock()
{
now=new GregorianCalendar();//每次触发*都使now表示为当前时间
}
//private ClockPanel clock;
private class ClockListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
setClock();//设置时间
}
}
public void run()
{
ClockListener clistener=new ClockListener();
Timer t=new Timer(1000,clistener);//每隔1000毫秒重复
t.start();
}
}