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); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10912.html