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

帮帮我!画直线和画矩形混在一块了!<很简短的代码>
以下是我的完整代码,当画完直线后再去画矩形,那么画出来的不是矩形,而是直线和矩形的杂合体。当再重打开程序先画矩形后画直线时,问题也是这样的,画出来的也还是杂合体。你运行一下试试。
我不知道从哪入手去解决,没有思路。
以下是完整代码:
//Draw.java
import   java.awt.*;
import   java.awt.event.*;
  class   Draw   {
  static     int   x0,y0,x1,y1,width,height;
public   static   void   main(String[]   args)
{

final   Frame   f=new   Frame( "   画图:余乐征 ");
f.addWindowListener(new   WindowAdapter()
{
public     void   windowClosing(WindowEvent   e)  
{
System.exit(0);
}
}
);
Point   p=new   Point(100,100);
f.setLocation(p);
f.setSize(700,600);
f.setBackground(Color.green);
f.setLayout(new   FlowLayout(FlowLayout.LEFT));

Button   bt1=new   Button( "直线 ");
f.add(bt1);
bt1.addActionListener(new   ActionListener()
{
public   void   actionPerformed(ActionEvent   e)  
{
f.addMouseListener(new   MouseAdapter()
{
public   void   mousePressed(MouseEvent   e)  
{
x0=e.getX();
y0=e.getY();
}
public   void   mouseReleased(MouseEvent   e)  
{
Graphics   gl=f.getGraphics();
gl.setColor(Color.blue);
gl.drawLine(x0,   y0,e.getX(),e.getY());
}
}
);
}
}
);

Button   bt2=new   Button( "矩形 ");
f.add(bt2);
bt2.addActionListener(new   ActionListener()
{
public   void   actionPerformed(ActionEvent   e)  
{
f.addMouseListener(new   MouseAdapter()
{
public   void   mousePressed(MouseEvent   e)  
{
x0=e.getX();
y0=e.getY();
}
public   void   mouseReleased(MouseEvent   e)  
{
x1=e.getX();
y1=e.getY();
width=x1-x0;
height=y1-y0;
Graphics   gr=f.getGraphics();
Graphics2D   g2d=(Graphics2D)   gr;
g2d.setStroke(new   BasicStroke(5));
gr.setColor(Color.red);
gr.drawRect(x0,   y0,   width,   height);
}
}
);
}
}
);
Button   bt3=new   Button( "清空 ");
f.add(bt3);
bt3.addActionListener(new   ActionListener()
{
public   void   actionPerformed(ActionEvent   e)
{
Graphics   g=f.getGraphics();
f.update(g);
}
}
);
f.show();
}
}


------解决方案--------------------
楼主给你弄好,逻辑上面错了。给分吧。
import java.awt.*;
import java.awt.event.*;
class Draw {
static int x0,y0,x1,y1,width,height;
public static void main(String[] args)
{

final Frame f=new Frame( " 画图:余乐征 ");
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
Point p=new Point(100,100);
f.setLocation(p);
f.setSize(700,600);
f.setBackground(Color.green);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
final MouseListener bevent1 = new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
x0=e.getX();
y0=e.getY();
}
public void mouseReleased(MouseEvent e)