Java 定时器类 Timer 使用方法
2018-07-20 来源:open-open
import java.awt.*; import java.awt.event.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.Timer; import javax.swing.*; public class SimpleTimer extends JWindow { public static void main(String[] args) { SimpleTimer simpleTimer = new SimpleTimer(); simpleTimer.pack(); simpleTimer.setAlwaysOnTop(true); simpleTimer.setVisible(true); } private Long startTimeMillis; private JLabel label; private SimpleDateFormat dateFormat; private Timer timer; public SimpleTimer() { initDateFormat(); initConponents(); resetTime(); updateLabelText(); startTimer(); } private void initDateFormat() { dateFormat = new SimpleDateFormat("HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } private void initConponents() { label = new JLabel(); label.setFont(new Font(label.getFont().getName(), Font.BOLD, 14)); label.setOpaque(true); label.setBackground(Color.black); label.setForeground(Color.white); label.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2)); getContentPane().add(label); final JPopupMenu popup = new JPopupMenu(); JMenuItem menuItem1 = new JMenuItem("Reset"); menuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { resetTime(); } }); popup.add(menuItem1); JMenuItem menuItem2 = new JMenuItem("Exit"); menuItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); popup.add(menuItem2); label.setComponentPopupMenu(popup); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON2 && e.getClickCount() == 1) { popup.setVisible(true); } } }); } private void resetTime() { startTimeMillis = Calendar.getInstance().getTimeInMillis(); } /** * ラベル更新 */ private void updateLabelText() { SwingUtilities.invokeLater(new Runnable() { public void run() { long elapsedTime = Calendar.getInstance().getTimeInMillis() - startTimeMillis; Date date = new Date(elapsedTime); label.setText(dateFormat.format(date)); } }); } /** * タイマー開始 */ private void startTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { updateLabelText(); } }, 0, 1000); } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
下一篇:js高级截取字符串功能
最新资讯
热门推荐