【问题标题】:Show stopwatch in JTextPane在 JTextPane 中显示秒表
【发布时间】:2013-01-05 02:12:23
【问题描述】:

我想将秒表放到 JPanel 中的 JTextPane 中,但它没有出现:/ 我不知道我是否可以将 (extends JLabel) 类中的对象放入 (extends JPanel) 类中。或许,这就是原因。

我的秒表课:

    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(); 
        ...     
    }

我该如何解决?

【问题讨论】:

    标签: java swing jpanel jtextpane stopwatch


    【解决方案1】:

    问题在于,虽然JTextPane 继承自Container 类,但add 方法不会将组件添加到JTextComponent 的文档中。只会呈现这些文档组件。

    替换:

    time.add(stopwatch);
    

    time.insertComponent(stopwatch);
    

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      相关资源
      最近更新 更多