【问题标题】:g.drawString Java, how to refresh string?g.drawString Java,如何刷新字符串?
【发布时间】:2015-08-03 09:38:04
【问题描述】:

请看一下我的代码。不知道在JPanel 上正确刷新我的变量elapsed。我使用g.drawString(var,x,y),但根本不重绘。 数字是一个在另一个上面写的。

我该如何解决这个问题?

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

public class CCrono {

    public static void main(String[] a) {
        TimeFrame frame = new TimeFrame();
        frame.setDefaultCloseOperation(3);
        frame.setVisible(true);
    }
}

/**
 * Frame with Time Panel
 */
class TimeFrame extends JFrame {

    //Constructor
    public TimeFrame() {
        //Dimentions
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screen = kit.getScreenSize();
        int height = screen.height;
        int wide = screen.width;
        //Size
        setSize(wide / 2, height / 2);
        //Localization
        setLocation(wide / 4, height / 4);
        //Title
        setTitle("Cronometer");
        //Panel
        TimePanel panel = new TimePanel();
        Container container = getContentPane();
        container.add(panel);
    }
}

/**
 * Panel showing elapsed time
 */
class TimePanel extends JPanel {

    String elapsed = "";
    int coo_x;
    int coo_y;
    int sec = 0;
    int min = 0;
    int hou = 0;

    TimePanel() {
        this.coo_x = 100;
        this.coo_y = 100;
        RepaintMethod paintMe = new RepaintMethod();
        Timer timer = new Timer(100, paintMe);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        sec++;
        if (sec == 60) {
            min++;
            sec = 0;
        }

        if (min == 60) {
            hou++;
            min = 0;
        }
        if (hou == 24) {
            hou =0 ;
         }

        elapsed = (hou < 10 ? "0" : "") + hou + ":" + (min < 10 ? "0" : "") + min + ":" + (sec < 10 ? "0" : "") + sec;
        g.drawString(elapsed, coo_x, coo_y);
    }

    private class RepaintMethod implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent ae) {
            repaint();
        }
    }
}

有什么建议吗?

谢谢大家。

【问题讨论】:

    标签: java swing timer paintcomponent


    【解决方案1】:

    打电话

    super.paintComponent(g);
    

    paintComponent方法中

    public void paintComponent(Graphics g) {
        super.paintComponent(g); // call here
        ...
    }
    

    从 oracle 站点读取 paint mechanism

    【讨论】:

    • @ManuelBalderrama 如果这个答案解决了你的问题,你应该accept it :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多