首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Repaint()不会清除框架

Repaint()不会清除框架
EN

Stack Overflow用户
提问于 2011-02-05 10:49:58
回答 3查看 19.4K关注 0票数 3
代码语言:javascript
复制
public class Graphics2DTest extends JPanel implements ActionListener{
private Timer time = new Timer(5,(ActionListener) this);
int x = 0,y = 0;
public void paintComponent(Graphics g){

    Graphics2D gui = (Graphics2D) g;
    Rectangle2D rectangle = new Rectangle2D.Double(x,y,100,150);
    gui.setPaint(Color.GREEN);
    gui.fill(rectangle);
    time.start();
}

public void actionPerformed(ActionEvent arg0) {
    x++;
    y++;
    repaint();
}
}

问题是repaint()应该清除框架并在该位置绘制矩形,但仍保留先前绘制的矩形。那么,该怎么做呢?请解释你的答案。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-02-05 11:18:42

您是否尝试过在paintComponent方法中调用super.paintComponent(g)?这将清除在JPanel中绘制的先前图像:

代码语言:javascript
复制
public void paintComponent(Graphics g){
  super.paintComponent(g);
  Graphics2D gui = (Graphics2D) g;
  Rectangle2D rectangle = new Rectangle2D.Double(x,y,100,150);
  gui.setPaint(Color.GREEN);
  gui.fill(rectangle);
  //time.start();
}

此外,不要在paintComponent方法中启动计时器或执行任何程序逻辑。首先,您不能绝对控制何时或是否调用该方法,其次,此方法必须只关注绘制,而不涉及其他任何内容,并且需要尽可能快。

例如:

代码语言:javascript
复制
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

import javax.swing.*;

public class Graphics2DTest extends JPanel implements ActionListener {
    private Timer time = new Timer(5, (ActionListener) this);
    int x = 0, y = 0;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D gui = (Graphics2D) g;
        Rectangle2D rectangle = new Rectangle2D.Double(x, y, 100, 150);
        gui.setPaint(Color.GREEN);
        gui.fill(rectangle);
        //time.start();
    }

    public void actionPerformed(ActionEvent arg0) {
        x++;
        y++;
        repaint();
    }

    public Graphics2DTest() {
        setPreferredSize(new Dimension(700, 500));
        time.start();
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Graphics2DTest");
        frame.getContentPane().add(new Graphics2DTest());
        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();
            }
        });
    }
}
票数 14
EN

Stack Overflow用户

发布于 2011-02-05 10:52:06

每次你也需要重新绘制背景。在绘制矩形之前添加用于绘制背景的代码。

票数 1
EN

Stack Overflow用户

发布于 2011-02-05 10:54:57

您需要先清除背景。

资源是这样的:

http://java.sun.com/products/jfc/tsc/articles/painting/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4904807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档