一个照着书上打的例子,画随即线;
3个类
第1个
package gui;
import java.awt.Color;
import java.awt.Graphics;
public class MyLine 
{
    private int x1;
    private int x2;
    private int y2;
    private int y1;
    private Color myColor;
    public MyLine(int x1,int y1,int x2,int y2,Color color)
    {
        this.x1=x1;
        this.y1=y1;
        this.x2=x2;
        this.y2=y2;
        myColor=color;
        
    }
    public void draw(Graphics g)
    {
        g.setColor(myColor);
        g.drawLine(x1,y1,x2,y2);
    }
}
第2个
package gui;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;public class DrawPanel extends JPanel
{
    private Random randomNumbers = new Random();
    private MyLine lines[];
    public DrawPanel()
    {
        setBackground( Color.WHITE );
        lines =new MyLine[5+randomNumbers.nextInt(5)];
        for (int count = 0;count < lines.length;count++)
        {
            int x1 = randomNumbers.nextInt(300);
            int y1 = randomNumbers.nextInt(300);
            int x2 = randomNumbers.nextInt(300);
            int y2 = randomNumbers.nextInt(300);
            Color color = new Color(randomNumbers.nextInt(256),randomNumbers.nextInt(256),randomNumbers.nextInt(256));
            lines[ count ] =new MyLine (x1,y1,x2,y2,color);
            
        }       
        
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        for ( MyLine line :lines)
        line.draw(g);
            
    }
}
第3个
package gui;import javax.swing.JFrame;public class TestDraw 
{
      public static void main(String args[])
      {
          DrawPanel panel = new DrawPanel();
          JFrame application = new JFrame();
          
          application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          application.add(panel);
          application.setSize(300,300);
          application.setVisible(true);
          
      }
    
}编译无问题,运行时错误提示是:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
        at gui.DrawPanel.<init>(DrawPanel.java:22)
        at gui.TestDraw.main(TestDraw.java:9)
应该是数组越界问题,但具体是哪里,刚接触JAVA不久的我找不出来.
帮帮我好吗/