编写程序,在窗体中连续显示当前的时间,java,求解
1个回答
展开全部
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Cat extends JFrame implements Runnable
{
private static final long serialVersionUID = 1L;
Thread thread;
public Cat()
{
setSize(200, 100);
setLayout(new BorderLayout());
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
start();
}
private Cat addComponents()
{
JPanel panel = new JPanel();
JButton run = new JButton("Start");
JButton wait = new JButton("Stop");
run.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
start();
}
});
wait.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
stop();
}
});
panel.add(run);
panel.add(wait);
add(panel, BorderLayout.SOUTH);
return this;
}
@Override
public void paint(Graphics g)
{
super.paint(g);
Calendar calendar = Calendar.getInstance();
String h = calendar.get(Calendar.HOUR_OF_DAY) + "";
h = h.matches("^\\d$") ? "0" + h : h;
String m = calendar.get(Calendar.MINUTE) + "";
m = m.matches("^\\d$") ? "0" + m : m;
String s = calendar.get(Calendar.SECOND) + "";
s = s.matches("^\\d$") ? "0" + s : s;
String str = h + ":" + m + ":" + s;
g.setFont(new Font("normal", Font.BOLD, 22));
g.drawString(str, getWidth() / 2 - 35, getHeight() / 2);
g.dispose();
}
public void start()
{
if(null == thread)
{
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
}
public synchronized void stop()
{
if(null != thread)
{
thread.interrupt();
thread = null;
notifyAll();
}
}
@Override
public void run()
{
Thread me = Thread.currentThread();
while(me == thread)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{}
repaint();
}
}
public static void main(String[] args)
{
new Cat().addComponents().setVisible(true);
}
}
追问
亲 能改成系统自动时间吗 年月日都有的
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询