日期:2014-05-20  浏览次数:20731 次

JAVA 如何清空或删除Canvas里的内容
JAVA 如何清空或删除Canvas里的内容

------解决方案--------------------
那给你一个例子吧
是清除JPanel的内容
和Canvas道理一样
一个面板上有字符串"HELLOWORLD!"
点击鼠标内容清除
调用repaint()如最小化再恢复
则字符串又显示

Java code

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

public class TT
{
    public static void main(String[] args)
    {
        MFrame m = new MFrame();
        m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        m.setVisible(true);
    }
}

class MFrame extends JFrame
{
    public static final int Default_Width = 200;
    public static final int Default_Height = 200;
    
    public MFrame()
    {
        setBounds(100, 100, Default_Width, Default_Height);
        
        Container con = getContentPane();
        MPanel p = new MPanel();
        con.add(p);
    }
}

class MPanel extends JPanel
{
    public MPanel()
    {
        addMouseListener(new
                        MouseAdapter()
                        {
                            public void mouseClicked(MouseEvent e)
                            {clearPanel();}
                        });
    }
    
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawString("HELLO WORLD!",30,30);
    }
    
    public void clearPanel()
    {
        Graphics g = getGraphics();
        int width = (int)(getBounds().getWidth());
        int height = (int)(getBounds().getHeight());
        g.clearRect(0, 0, width, height);
    }
}