如题,先给出代码:
//DrawPanel.java 画板类,完成画图和鼠标的响应
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
abstract class MyShape
{
abstract public void draw(Graphics g,int x,int y,int width,int height);
}
class MyRectangle extends MyShape
{
public void draw(Graphics g,int x,int y,int width,int height)
{
g.drawRect(x,y,width,height);
}
}
class MyCircle extends MyShape
{
public void draw(Graphics g,int x,int y,int width,int height)
{
g.drawOval(x,y,width,height);
}
}
class DrawPanel extends JPanel
{
int x1,y1,x2,y2;
MyShape ms=null;
ArrayList vt=new ArrayList();//存坐标
ArrayList vt2=new ArrayList();//形状
DrawPanel()
{
this.addMouseListener(new ml()); //鼠标按下//鼠标弹起
this.addMouseMotionListener(new nl()); //鼠标拖动事件
}
public void setshape(MyShape ms)
{
this.ms=ms;
}
public void cls()
{
vt.clear();
vt2.clear();
x1=y1=x2=y2=0;
currentShape=0;
repaint();
}
//重写绘图方法
public void paint(Graphics g)
{
g.clearRect(0,0,this.getWidth(),this.getHeight());
for (int i = 0; i<vt.size(); i++)
{
Rectangle re=(Rectangle)vt.get(i);
int a=(re.x<re.width)?re.x:re.width;
int b=(re.y<re.height)?re.y:re.height;
((MyShape)vt2.get(i)).draw(g,a,b,Math.abs(re.width-re.x),Math.abs(re.height-re.y));
}
int x=(x1<x2)?x1:x2;
int y=(y1<y2)?y1:y2;
//画出当前选中图形
ms.draw(g,x,y,Math.abs(x2-x1),Math.abs(y2-y1));//---------------------------Here
}
//鼠标事件
class ml extends MouseAdapter
{ //鼠标按下
public void mousePressed(MouseEvent e)
{
x1=e.getX();
y1=e.getY();
}
public void mouseReleased(MouseEvent e)
{ //鼠标弹起
Rectangle rea=new Rectangle(x1,y1,x2,y2);
vt.add(rea);
vt2.add(ms);
}
}
//鼠标拖动事件
class nl extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent e)
{
x2=e.getX();
y2=e.getY();
repaint();
}
}
}
///////////////////////////////////////////////////////////////////////////////////
//MainFrame.java 主框架类
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MainFrame extends JFrame
{
DrawPanel drawPanel = new DrawPanel();
JButton bt_cls = new JButton("清空");
JButton btnRect,btnCircle;
MainFrame()
{
this.setSize(600,500);
this.setTitle("JAVA制作的画图板");
//=============================西部面板
JPanel pw=new JPanel();
pw.setPreferredSize(new Dimension(120,500));
JPanel pw_1=new JPanel();
pw.add(pw_1);
pw_1.setLayout(new GridLayout(5,2));
//按下矩形按钮时
btnRect =new JButton(new ImageIcon("0.png"));
pw_1.add(btnRect);
btnRect.addActionListener(new m());
//按下圆形按钮时
btnCircle =new JButton(new ImageIcon("1.png"));
pw_1.add(btnCircle);
btnRect.addActionListener(new m());
//按下清除按钮时
pw_1.add(bt_cls);
bt_cls.addActionListener(new m());
this.add(pw,BorderLayout.WEST);
this.add(drawPanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
class m implements ActionListener
{
public void actionPerformed(ActionEvent e)
{