tags:

views:

26

answers:

2

as i change string but it remain as it is in jlable. i want to update that string from particular timeperiod

+1  A: 

Try to use SwingUtilities.invokeLater or invokeAndWait.

Like in the following code.

Hope it helps.

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class LabelUpdater {
    public static void main(String[] args) {
        LabelUpdater me = new LabelUpdater();
        me.process();
    }

    private JLabel label;

    private void process() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new JPanel(new BorderLayout()));
                label = new JLabel(createLabelString(5));
                frame.getContentPane().add(label);
                frame.setSize(300, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });

        snooze();
        for (int i = 5; i >= 1; i--) {
            final int time = i - 1;
            snooze();
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    label.setText(createLabelString(time));

                }

            });

        }

    }

    private void snooze() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    private String createLabelString(int nbSeconds) {
        return "Still " + nbSeconds + " seconds to wait";
    }
}
Laurent K
thanks it worked ..:)
nicky
+1  A: 

Use a javax.swing.Timer (tutorial). This will ensure thread safety by executing on the event dispatch thread.

public class TimerDemo {
  public static void main(String[] args) {
    final int oneSecondDelay = 1000;
    final JLabel label = new JLabel(Long.toString(System.currentTimeMillis()));
    ActionListener task = new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        label.setText(Long.toString(System.currentTimeMillis()));
      }
    };
    new javax.swing.Timer(oneSecondDelay, task).start();
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new FlowLayout());
    frame.add(label);
    frame.pack();
    frame.setVisible(true);
  }
}
McDowell