以下代码很简单,就是原本在长方形框内有3个连续的小正方形,鼠标点击以下,减少一个。
但为何不能减少呢?head = head.next;这句代码没有起作用,为什么啊为什么?
public class TCS1
{
    public static void main(String[] args) {
        // TODO code application logic here
        Frame f = new Frame();
        f.setSize(250, 320);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}class Frame extends JFrame
{
    public Frame()
    {
        Component c = new Component();
        add(c);
    }
}class Component extends JComponent
{
    public Component()
    {
        //3个正方形
        head = new list();
        list p = head;
        for(int i = 0; i < 3; i++)
        {
            p.rect = new Rectangle2D.Double(30 + i * 10, 30, 10, 10);
            list q = new list();
            p.next = q;
            p = q;
        }        this.addMouseListener(new MouseAdapter()
        {
            public void mousePressed(MouseEvent e)
            {
                automatism(head);
                repaint();
            }
        });
    }    public void paintComponent(Graphics g)
    {
        Graphics2D g2d = (Graphics2D)g;        //一个长方形的边框
        Line2D upLine = new Line2D.Double(20, 20, 220, 20);
        Line2D leftLine = new Line2D.Double(20, 20, 20, 270);
        Line2D downLine = new Line2D.Double(20, 270, 220, 270);
        Line2D rightLine = new Line2D.Double(220, 20, 220, 270);
        g2d.draw(upLine);
        g2d.draw(leftLine);
        g2d.draw(downLine);
        g2d.draw(rightLine);        list p = head;
        while(p.next != null)
        {
            g2d.draw(p.rect);
            g2d.fill(p.rect);
            p = p.next;
        }
    }    public void automatism(list head)
    {
        head = head.next;
    }    private list head;
}class list
{
    public list()
    {
        rect = null;
        next = null;
    }    protected Rectangle2D rect;
    protected list next;
}

解决方案 »

  1.   


     public void automatism(list head)
      {
      head = head.next;//改成this.head = head.next;
      }
      

  2.   

    thanks very much
    但,为什么,能告诉我原因么?
      

  3.   

    Component c = new Component();
    这句能编译通过么?你用的什么版本的JDK?
      

  4.   


    public void automatism(list head)
      {
      head = head.next;//等号前后的head都是参数head,而不是你的成员变量head,
    //加了this.才表示是更改你的成员变量
      }
      

  5.   

    Component是我自己设计的类名,本人很懒~~~
    class Component extends JComponent