Graphics的方法 void clearRect(int x, int y, int width, int height) 通过使用当前绘图表面的背景色进行填充来清除指定的矩形。
那给你一个例子吧 是清除JPanel的内容 和Canvas道理一样 一个面板上有字符串"HELLOWORLD!" 点击鼠标内容清除 调用repaint()如最小化再恢复 则字符串又显示 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); } }
void clearRect(int x, int y, int width, int height)
通过使用当前绘图表面的背景色进行填充来清除指定的矩形。
是清除JPanel的内容
和Canvas道理一样
一个面板上有字符串"HELLOWORLD!"
点击鼠标内容清除
调用repaint()如最小化再恢复
则字符串又显示
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);
}
}