2010-01-13 4 views

답변

1

SwingUtilities.invokeLater 또는 invokeAndWait를 사용해보십시오.

다음 코드와 유사합니다.

희망이 있습니다.

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"; 
    } 
} 
+0

감사합니다. :) :) – nicky

1

사용하십시오 javax.swing.Timer (tutorial). 이렇게하면 이벤트 발송 스레드에서 실행하여 스레드 안전을 보장합니다.

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); 
    } 
} 
관련 문제