[求助]怎么样消除之前画过的轨迹
import java.awt.*;import java.awt.event.*;
import javax.swing.*;
import javax.swing.*;
public class J_DrawDemo extends JFrame implements ActionListener
{
panel pl=new panel();//生成panel的一个对象
JPanel jpb=new JPanel();//生成jpb容器,用于放置按钮
JButton jb1;
JButton jb2;
JButton jb3;
JButton jb4;
public J_DrawDemo()
{
super("画图程序");
jb1=new JButton(" 画直线 ");//生成各个按钮对象
jb2=new JButton(" 画椭圆 ");
jb3=new JButton(" 画矩形 ");
jb4=new JButton(" 自由绘图 ");
jb1.addActionListener(this);//注册按钮监听器
jb2.addActionListener(this);
jb3.addActionListener(this);
jb4.addActionListener(this);
jpb.setBorder(BorderFactory.createEtchedBorder());//设置jpb边界
pl.setBorder(BorderFactory.createEtchedBorder());//设置pl边界
jpb.add(jb1);//在按钮加入jpb
jpb.add(jb2);
jpb.add(jb3);
jpb.add(jb4);
ButtonGroup buttonGroup=new ButtonGroup();//定义一个按钮组,实现按钮互斥
Container cp=getContentPane();//获得容器
cp.add(jpb,BorderLayout.SOUTH);//将工具条加入容器
cp.add(pl,BorderLayout.CENTER);//将pl加入容器
cp.setBackground(Color.white);
setSize(600,500);
this.setResizable(false);//设置窗体大小不可变
setLocation(200,100);//设置窗体在屏幕的显示位置
setVisible(true);//设置窗体可见
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//退出方式
}
public void actionPerformed(ActionEvent e)//按钮实现动作并执行
{
if(e.getSource()==jb1)
pl.shape=0;
if(e.getSource()==jb2)
pl.shape=1;
if(e.getSource()==jb3)
pl.shape=2;
if(e.getSource()==jb4)
pl.shape=3;
}
public static void main(String[] args)
{
new J_DrawDemo();//调用J_DrawDemo类构造函数
}
}
class panel extends JPanel //定义一个JPanel的字类
{
int shape=-1;
int startX=0,startY=0;
int endX=0,endY=0;
int flag=0;
public panel()
{
//setBackground(Color.white);
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)//鼠标按下事件
{
if(shape==3)//当为自由画线时,执行下面语句
{
endX=e.getX();
endY=e.getY();
}
else
{
startX=e.getX();
startY=e.getY();
}
}
}
);//注册鼠标动作监听器
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)//鼠标拖拽事件
{
if(shape==3)//当为画自由线时拖动鼠标动作才执行
{
startX=endX;
startY=endY;
endX=e.getX();
endY=e.getY();
repaint();
}
else//当选择画图功能不是自由画线时,则执行下面语句
{
endX=e.getX();
endY=e.getY();
repaint();
}
}
}
);
}
public void paintComponent(Graphics g)//实现画图
{
//super.paintComponent(g);
switch(shape)
{
case 0:
g.drawLine(startX,startY,endX,endY);//画直线
break;
case 1:
int width=endX-startX;
int height=endY-startY;
g.drawOval(startX,startY,width,height);//画椭圆
break;
case 2:
width=endX-startX;
height=endY-startY;
g.drawRect(startX,startY,width,height);//画矩形
break;
case 3:
g.drawLine(startX,startY,endX,endY);//自由画线
break;
}
}
}