Graphics.drawString()绘制我的旧字符串

daG*_*vis 4 java graphics awt drawstring

我正在研究简单的计数器.我的问题是drawString()方法在旧的字符串上绘制新的字符串.以前如何清除旧的?码...

package foobar;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class board extends JPanel implements Runnable {

    Thread animator;
    int count;

    public board() {
        this.setBackground( Color.WHITE );
        count = 0;
        animator = new Thread( this );
        animator.start();
    }

    @Override
    public void run() {
        while( true ) {
            ++count;
            repaint();
            try {
                animator.sleep( 1000 );
            } catch ( InterruptedException e ) {}
        }
    }

    @Override
    public void paint( Graphics Graphics ) {
        Graphics.drawString( Integer.toString( count ), 10, 10 );
    }
}
Run Code Online (Sandbox Code Playgroud)

PS我是Java的新手,所以请不要害怕告诉我在代码中应该修复的其他内容......

Hov*_*els 7

您的代码中的几个问题:

  • 在Swing GUI中没有while(true)循环或Thread.sleep.请改用Swing Timer.
  • 覆盖JPanel的paintComponent,而不是它的paint方法.
  • paintComponent(Graphics g)中的第一个调用应该是super.paintComponent(g),因此你的JPanel可以保持住宅并摆脱旧的图形.

编辑:

  • 我的坏,你的while(true)和Thread.sleep(...)起作用,因为它们在后台线程中,但是,......
  • Thread.sleep是一个静态方法,应该在类,Thread和.上调用
  • 我仍然认为Swing Timer会更容易实现.
  • 更简单的是甚至不使用paint或paintComponent方法,而是简单地为显示器设置JLabel的文本.

例如,

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Board2 extends JPanel {
   private static final int TIMER_DELAY = 1000;

   private int counter = 0;
   private JLabel timerLabel = new JLabel("000");

   public Board2() {
      add(timerLabel);
      new Timer(TIMER_DELAY, new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            counter++;
            timerLabel.setText(String.format("%03d", counter));
         }
      }).start();
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("Board2");
      frame.getContentPane().add(new Board2());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
Run Code Online (Sandbox Code Playgroud)