2013-01-05 47 views
0

我想將我的秒錶放到JPanel的JTextPane中,但它沒有出現:/我不知道是否可以將類(extends JLabel)中的對象放在類(extends JPanel)中。也許,這是原因。在JTextPane中顯示秒錶

我的秒錶類:

public class StopWatch extends JLabel implements ActionListener { 

    private DecimalFormat df = new DecimalFormat("0.0"); 
    private Timer timer = new javax.swing.Timer(100, this); 
    private long now = System.currentTimeMillis(); 

    public StopWatch() { 
     this.setText(when()); 
    } 

    public void actionPerformed(ActionEvent ae) { 
     setText(when()); 
    } 

    public void start() { 
     timer.start(); 
    } 

    public void stop() { 
     timer.stop(); 
    } 

    private String when() { 
     return df.format((System.currentTimeMillis() - now)/1000d); 
    } 
} 

這是我如何使用它:

public class Tlo extends JPanel { 
     ....  
     StopWatch stopwatch = new StopWatch(); 
     JTextPane time = new JTextPane(); 
     time.setFont(new Font("Arial", Font.PLAIN, 28)); 
     time.setBounds(135,598,115,34); 
     time.setBackground(new Color(182, 221, 232)); 
     time.setEditable(false); 
     time.add(stopwatch); 
     add(time); 
     stopwatch.start(); 
     ...  
    } 

我該如何解決?

回答

0

問題是,儘管JTextPane繼承自Container類,但add方法不會將組件添加到JTextComponent的文檔中。只有這些文檔組件纔會被渲染。

替換:

time.add(stopwatch); 

time.insertComponent(stopwatch);