Re: Timer Problem December 19, 2013 04:13PM |
Admin Registered: 15 years ago Posts: 2,094 |
Language: Javaimport javax.swing.*; import java.awt.*; import java.util.Timer; import java.util.TimerTask; public class SleepTest3 extends TimerTask { private JLabel label; public static void main(final String[] args) { SwingUtilities.invokeLater(new SleepTest3()); } @Override public void run() { if (label == null) { init(); return; } if (SwingUtilities.isEventDispatchThread()) { final int num = Integer.parseInt(label.getText()); label.setText(Integer.toString(num + 1)); } else { SwingUtilities.invokeLater(this); } } private void init() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (final Exception e) { e.printStackTrace(); } final JFrame frame = new JFrame("Sleep test"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLayout(new GridBagLayout()); final JLabel counter = new JLabel("0"); final JLabel counterFixedRate = new JLabel("0"); final Font font = counter.getFont().deriveFont(20F); counter.setFont(font); counterFixedRate.setFont(font); final GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = 1; frame.add(counter, gbc); gbc.gridy = 2; frame.add(counterFixedRate, gbc); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); final Timer timer = new Timer(); final SleepTest3 test = new SleepTest3(); test.label = counter; timer.schedule(test, 0, 1000); final SleepTest3 testFixedRate = new SleepTest3(); testFixedRate.label = counterFixedRate; timer.scheduleAtFixedRate(testFixedRate, 0, 1000); } }