这个程序有点问题:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class J_Draw extends JFrame implements ActionListener
{
int x=0,y=0;//当前坐标
int startX=0,startY=0;//开始坐标
int width=0,height=0;//初始化宽度与高度为零
Button jb1,jb2,jb3;
int J_switch;//选择画图类型控制变量
public J_Draw()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout(0));
jb1=new Button("画自由线");
jb2=new Button("画矩形");
jb3=new Button("画椭圆");
jb1.addActionListener(this);//注册监听器
jb2.addActionListener(this);
jb3.addActionListener(this);
cp.add(jb1);//添加按钮到容器
cp.add(jb2);
cp.add(jb3);
setBackground(Color.white);
setSize(400,400);
setVisible(true);
}
public void actionPerformed(ActionEvent e)//按钮事件
{
if(e.getSource()==jb1)//判断按钮所触发的事件为画自由线
{
J_switch=0;
FreeDraw();//调用自由画线方法
}
if(e.getSource()==jb2)
{
J_switch=1;
Rect_OvalDraw();
}
if(e.getSource()==jb3)
{
J_switch=2;
Rect_OvalDraw();
}
}
public void FreeDraw()/////////////////////////////////自由画线动作函数
{
addMouseListener(new MouseAdapter()//定义鼠标内部类
{
public void mousePressed(MouseEvent e)
{
x=e.getX();
y=e.getY();
startX=x;
startY=y;
repaint();
}
}
);//结束
addMouseMotionListener(new MouseMotionAdapter()//定义鼠标内部类
{
public void mouseDragged(MouseEvent e)
{
startX=x;
startY=y;
x=e.getX();
y=e.getY();
repaint();
}
}
);//结束
}
public void Rect_OvalDraw()////////////////////////////////画矩形与椭圆动作函数
{
addMouseListener(new MouseAdapter()//定义鼠标内部类
{
public void mousePressed(MouseEvent e)
{
startX=e.getX();
startY=e.getY();
}
}
);//内部类结束
addMouseListener(new MouseAdapter()//定义鼠标内部类
{
public void mouseReleased(MouseEvent e)
{
width=e.getX()-startX;
height=e.getY()-startY;
repaint();
}
}
);//结束
}
public void paint(Graphics g)/////////实现画图功能
{
if(J_switch==0)
g.drawLine(startX,startY,x,y);
else if(J_switch==1)
g.drawRect(startX,startY,width,height);
// g.clearRect(startX+1,startY+1,width-1,height-1);
else if(J_switch==2)
g.drawOval(startX,startY,width,height);
}
public static void main(String[] args)
{
J_Draw app=new J_Draw();
Container cp=app.getContentPane();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}