2012-03-28 79 views
1

我试图做一个JDialog,它会向用户显示一个JLabel上的动态消息。 消息应该是从1到10的计数(并且它应该每秒更改一个数字)。 事情是,当我调试它时 - 它停在“dia.setVisible(true)”之后;“ ,除非我关闭JDialog,否则不会继续。 有没有可能的修复方法? 谢谢。通过定时器在JDialog中设置动态JLabel文本

看看代码:

@Override 
public void run() { 

    dia = new JDialog(parentDialog, true); 
    dia.setLocationRelativeTo(parentFrame); 


    String text = "Text "; 
    dia.setSize(300, 150); 
    jl = new JLabel(text); 
    dia.getContentPane().add(jl); 
    dia.setVisible(true); 
    for (int i = 0; i < 10; i++) { 
     try { 
      Thread.sleep(1000); 
      jl.setText(text + " " + i); 

     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

} 

回答

3
  • 没有为Swing GUI的使用Thread.sleep(int),造成直到Thread.sleep(int)冻结结束

  • 使用Swing Timer,而不是由Thread.sleep(int)

  • 使用不使用dia.setSize(300, 150)锁定Swing GUI的,学习如何LayoutManager工作

2

setVisible是在JDialog上的阻塞调用。您应该启动其他主题并将Runnable传递给它。 Runnable.run()方法应该包含你的循环。

+0

同意的SwingWorker绝对是更好的选择。我应该试着一劳永逸地学习这个API(当然,我知道它,但我从来没有用过它,所以我从不太确定) – 2012-03-28 12:57:43

0

确保jl被定义为final

... 
dia.getContentPane().add(jl); 

new Thread(new Runnable() { 
    for (int i = 0; i < 10; i++) { 
     try { 
      Thread.sleep(1000); 
      jl.setText(text + " " + i); 

     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
}).run(); 

dia.setVisible(true); 
2

看一看这个代码示例,这是正确的方式来使用动态文本与javax.swing.Timer Tutorials的帮助,而不是使用Thread.sleep(...)啄,

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class DialogExample extends JDialog 
{ 
    private Timer timer; 
    private JLabel changingLabel; 
    private int count = 0; 
    private String initialText = "TEXT"; 

    private ActionListener timerAction = new ActionListener() 
    { 
     public void actionPerformed(ActionEvent ae) 
     { 
      count++; 
      if (count == 10) 
       timer.stop(); 
      changingLabel.setText(initialText + count); 
     } 
    }; 

    private void createDialog() 
    { 
     setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 
     setLocationByPlatform(true); 

     JPanel contentPane = new JPanel(); 
     changingLabel = new JLabel(initialText); 
     contentPane.add(changingLabel); 

     add(contentPane); 

     pack(); 
     setVisible(true); 
     timer = new Timer(1000, timerAction); 
     timer.start(); 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new DialogExample().createDialog(); 
      } 
     }); 
    } 
}