无法访问子类中的父类变量值

时间:2017-11-04 20:19:11

标签: java

我遇到了一个问题,试图从Child Class(Balloon())中的Parent Class(DrawingPanel())访问变量(R)的值。

我在DrawingPanel()的类构造函数中将公共整数R设置为0。像这样:

public class DrawingPanel extends JPanel implements MouseListener, 
MouseMotionListener, KeyListener 
{
...
public int R;
// Constructor:
public DrawingPanel() {
    setBackground(Color.WHITE);
    addMouseListener(this);
    addMouseMotionListener(this);
    addKeyListener(this);
    ...
    R = 0;
}

通过mousePressed()方法(DrawingPanel()类的一部分)检测鼠标单击JPanel中的Balloon对象。见下文:

// Called when the mouse is clicked on the drawing panel.
// If inside a balloon, makes it "active", remembers the offsets
// of the click from the center.
// If on the border of a balloon, makes it "active", remembers the
// distance of the click from the center.
public void mousePressed(MouseEvent e) {
    ...
    R = 1;
    System.out.print(R);
    ...
}

在Child Class,Balloon()中,继承DrawingPanel()父类,并将R的值打印到控制台。像这样:

     /**
     * Represents a balloon in the BalloonDraw program.
     * Author: Willy Bolly
     * Ver 1.0 Created 12/31/17
     */

    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;

    import javax.swing.JPanel;

    public class Balloon extends DrawingPanel
    {
       int xCenter, yCenter, radius, rotate = RotateState();
       Color color;

      /**
       * Constructs a balloon with the center at (0, 0),
       * radius 50, and blue color
       */
      public Balloon()
      {  
        xCenter = 0;
        yCenter = 0;
        radius = 50;
        color = Color.BLUE;
      }

      /**
       * Constructs a balloon with a given center, radius and color
       * @param x x-coordinate of the center
       * @param y y-coordinate of the center
       * @param r radius of the balloon
       * @param c color of the balloon
       */
      public Balloon(int x, int y, int r, Color c)
      {   
        xCenter = x;
        yCenter = y;
        radius = r;
        color = c;

      }


      /**
       * Returns the x-coordinate of the center.
       */
      public int getX()
      {
        System.out.println(rotate);   
        return xCenter;
      }

      /**
       * Returns the y-coordinate of the center.
       */
      public int getY()
      {
        return yCenter;
      }

      /**
       * Returns the radius of this balloon.
       */
      public int getRadius()
      {
        return radius;
      }

      /**
       * Returns the color of this balloon.
       */
      public Color getColor()
      {
        return color;
      }

      /**
       * Returns the distance from a given point to the
       * center of this balloon.
       * @param x, y coordinates of the point
       */
      public double distance(int x, int y)
      {
        double dx = x - xCenter;
        double dy = y - yCenter;
        return Math.sqrt(dx*dx + dy*dy);
      }

      /**
       * Moves the center of this balloon to (x, y)
       * @param x x-coordinate of the new center
       * @param y y-coordinate of the new center
       */
      public void move(int x, int y)
      {
        xCenter = x;
        yCenter = y;
      }

      /**
       * Sets the radius of this balloon to r
       * @param r new radius
       */
      public void setRadius(int r)
      {
        radius = r;
      }

      /**
       * Returns true if a given point is strictly inside this balloon;
       * otherwise returns false
       * @param x, y coordinates of the point
       */
      public boolean isInside(int x, int y)
      {
        return distance(x, y) < 0.9 * radius;
      }

      /**
       * Returns true if a given point is on the border of this balloon;
       * otherwise returns false
       * @param x, y coordinates of the point
       */
      public boolean isOnBorder(int x, int y)
      {   
        double d = distance(x, y);
        return d >= 0.9 * radius && d <= 1.1 * radius;
      }

      //Returns R value from DrawingPanel() class
        public int RotateState()
      {
        return R;
      }

      /**
   * Draws a solid circle if makeItFilled is true and
   * outline only if makeItFilled is false
   * @param g graphics context
   * @param makeItFilled draws a solid circle if true
   */
  public void draw(Graphics g, boolean makeItFilled)
  {


  }
 }

由于某种原因,Balloon()类仅获取并输出在DrawingPanel()类的构造函数中声明的R的值。但是,当mousePressed()方法启动时,变量R更改后,它无法返回变量R的更新值。

有人可以确定为什么会出现这个问题吗?非常感谢您的反馈。

4 个答案:

答案 0 :(得分:0)

Balloon课程中,您应该覆盖mouseClicked方法并实现其特定于类的逻辑。

所以,将其添加到Balloon类:

@Override
public void mousePressed(MouseEvent e) {
    super.mousePressed(e);
    // Do stuff with R
    getX();
}

答案 1 :(得分:0)

我认为有可能因为继承,BaloonDrawingPanel的实例被视为单独的,因此有自己的变量和值。 mousePressed方法会将DrawingPanel.R的值更改为1,但不会将Baloon.R的值更改为mousePressed

覆盖Baloon类中的import re if re.findall('[\!\$\%\^\&\*\_\-\+\=]', name): points += 1 方法,如上一个答案中建议的那样,可能会解决您的问题。

答案 2 :(得分:0)

更新#1

我找到了另一种让程序的旋转功能正常工作的方法。

我将变量R的名称更改为rotate

DrawingPanel()课程中,我有以下内容:

public class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener, KeyListener {
    private ArrayList<Balloon> balloons;
    private Balloon activeBalloon;
    private Color color;
    private DrawingPanel canvas;
    private boolean picked, stretching;
    private int offsetX, offsetY;
    private double offsetR;
    int rotate;

    // Constructor:
    public DrawingPanel() {
        setBackground(Color.WHITE);
        addMouseListener(this);
        addMouseMotionListener(this);
        addKeyListener(this);
        balloons = new ArrayList<Balloon>();
        activeBalloon = null;
        picked = false;
        stretching = false;
        color = Color.BLUE;
        rotate = 0;
        System.out.println("This is" + rotate + "from the constructor of DrawingPanel()");
    }
 // Called from controlPanel when the "Add balloon" button is clicked.
// Places a new balloon with a random radius and the current color
// at the center of the drawing panel.
public void addBalloon(int shape) {
    int w = getWidth();
    int h = getHeight();
    int radius = 10 + (int) (Math.random() * w / 2);
    switch (shape) {
    case 1:
        activeBalloon = new RoundBalloon(w / 2, h / 2, radius, color);
        break;
    case 2:
        activeBalloon = new OvalBalloon(w / 2, h / 2, radius, color);
        break;
    case 3:
        activeBalloon = new SquareBalloon(w / 2, h / 2, radius, color);
        break;
    case 4:
        activeBalloon = new FancyBalloon(w / 2, h / 2, radius, color);
        break;
    default:
        activeBalloon = new RoundBalloon(w / 2, h / 2, radius, color);
        break;
    }
    balloons.add(activeBalloon);
    repaint();
}
// Repaints this panel. If activeBalloon is set, paints it on top.
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (Balloon b : balloons) {
        if (!picked || b != activeBalloon)
        {
            System.out.println("This is rotate" + rotate + "from paintComponent()");
            //Added rotate parameter which takes the rotate value 
            //from mousePressed() method and passes to the draw()
            //object being drawn 
            b.draw(g, true, rotate);

        }

    }
    if (picked && activeBalloon != null)
        //Added rotate parameter which takes the rotate value 
        //from mousePressed() method and passes to the draw()
        //method for the balloon object being drawn 
        activeBalloon.draw(g, false, rotate);
}

// Called when the mouse is clicked on the drawing panel.
// If inside a balloon, makes it "active", remembers the offsets
// of the click from the center.
// If on the border of a balloon, makes it "active", remembers the
// distance of the click from the center.
public void mousePressed(MouseEvent e) {
    rotate = 1;
    System.out.println("This is the value of rotate" + rotate + "from the mousePressed() method in DrawingPanel() class.");
    int x = e.getX();
    int y = e.getY();
    picked = false;
    for (int k = balloons.size() - 1; k >= 0 && !picked; k--) {
        Balloon b = balloons.get(k);
        if (b.isInside(x, y)) {
            picked = true;
            offsetX = x - b.getX();
            offsetY = y - b.getY();
            stretching = false;
            activeBalloon = b;

        } else if (b.isOnBorder(x, y)) {
            picked = true;
            offsetR = b.distance(x, y) - b.getRadius();
            stretching = true;
            activeBalloon = b;
        }
    }
    if (picked)
        repaint();

}
...
}

在Balloon()类的子类之一SquareBalloon()中,我有以下内容:

public class SquareBalloon extends Balloon {
    public SquareBalloon() {
    }

    /**
     * Constructs a balloon with a given center, radius and color
     * 
     * @param x
     *            x-coordinate of the center
     * @param y
     *            y-coordinate of the center
     * @param r
     *            radius of the balloon
     * @param c
     *            color of the balloon
     */
    public SquareBalloon(int x, int y, int r, Color c) {
        super(x, y, r, c);
    }

    /**
     * Draws a solid circle if makeItFilled is true and outline only if
     * makeItFilled is false
     * 
     * @param g
     *            graphics context
     * @param makeItFilled
     *            draws a solid circle if true
     */
    public void draw(Graphics g, boolean makeItFilled, int rotate) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.WHITE);
        g.setColor(color);
        System.out.println("This is the value of rotate" + rotate + "from the draw() method of SquareBalloon() class.");
        if (makeItFilled) {
            Rectangle rect2 = new Rectangle(xCenter - radius, yCenter - radius, radius, radius);
            //Value from rotate parameter is used for the rotation
            if (rotate == 1) {
                System.out.println("This is the value of rotate" + rotate
                        + "from the makedItFilled if statement in draw() method of SquareBalloon() class.");
                g2d.rotate(90);
            }
            g2d.fill(rect2);

        } else {
            Rectangle rect2 = new Rectangle(xCenter - radius, yCenter - radius, radius, radius);
            //Value from rotate parameter is used for the rotation
            if (rotate == 1) {
                System.out.println("This is the value of rotate" + rotate
                        + "from the other if statement in draw() method of SquareBalloon() class.");
                g2d.rotate(90);
            }
            g2d.draw(rect2);

        }
    }
}

旋转很好。但现在的麻烦是我无法弄清楚如何重置rotate参数的值,以便在创建新对象时不会发生旋转。

在我的代码的当前格式中,该参数仅考虑在rotate方法上设置的变量mousePressed()的值。

有人可以建议我应该做什么,以便旋转参数考虑到变量rotate的值的变化,而不是mousePressed()方法吗?

答案 3 :(得分:0)

更新#2

我修复了上一篇文章(更新#1)中描述的问题。

DrawingPanel()类如下所示:

   public class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener, KeyListener {
    private ArrayList<Balloon> balloons;
    private Balloon activeBalloon;
    private Color color;
    private DrawingPanel canvas;
    private boolean picked, stretching;
    private int offsetX, offsetY;
    private double offsetR;
    int rotate;

    // Constructor:
    public DrawingPanel() {
        setBackground(Color.WHITE);
        addMouseListener(this);
        addMouseMotionListener(this);
        addKeyListener(this);
        balloons = new ArrayList<Balloon>();
        activeBalloon = null;
        picked = false;
        stretching = false;
        color = Color.BLUE;
        rotate = 0;
        System.out.println("This is" + rotate + "from the constructor of DrawingPanel()");
    }

    // Called from controlPanel when the "Pick color" button is clicked.
    public void pickColor() {
        Color pickedColor = JColorChooser.showDialog(this, "Pick a color", color);
        if (pickedColor != null)
            color = pickedColor;
    }

    // Returns the current color.
    public Color getColor() {
        return color;
    }

    // Called from controlPanel when the "Add balloon" button is clicked.
    // Places a new balloon with a random radius and the current color
    // at the center of the drawing panel.
    public void addBalloon(int shape) {
        int w = getWidth();
        int h = getHeight();
        int radius = 10 + (int) (Math.random() * w / 2);
        switch (shape) {
        case 1:
            activeBalloon = new RoundBalloon(w / 2, h / 2, radius, color);
            break;
        case 2:
            activeBalloon = new OvalBalloon(w / 2, h / 2, radius, color);
            break;
        case 3:
            activeBalloon = new SquareBalloon(w / 2, h / 2, radius, color);
            break;
        case 4:
            activeBalloon = new FancyBalloon(w / 2, h / 2, radius, color);
            break;
        default:
            activeBalloon = new RoundBalloon(w / 2, h / 2, radius, color);
            break;
        }
        balloons.add(activeBalloon);
        repaint();
    }

    // Repaints this panel. If activeBalloon is set, paints it on top.
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Balloon b : balloons) {
            if (!picked || b != activeBalloon)
            {
                //Added this check to restore original angle of balloon 
                //objects. 
                if(rotate > 1)
                    rotate = 0;
                System.out.println("This is rotate" + rotate + "from paintComponent()");
                b.draw(g, true, rotate);

            }

        }
        if (picked && activeBalloon != null)
            activeBalloon.draw(g, false, rotate);
    }

    // Called when the mouse is clicked on the drawing panel.
    // If inside a balloon, makes it "active", remembers the offsets
    // of the click from the center.
    // If on the border of a balloon, makes it "active", remembers the
    // distance of the click from the center.
    public void mousePressed(MouseEvent e) {
        //Value for parameter rotate is set here on mouse click
        //Changed the counter so its value is not set to 1
        //but it would add up. 
        rotate++;
        System.out.println("This is the value of rotate" + rotate + "from the mousePressed() method in DrawingPanel() class.");
        int x = e.getX();
        int y = e.getY();
        picked = false;
        for (int k = balloons.size() - 1; k >= 0 && !picked; k--) {
            Balloon b = balloons.get(k);
            if (b.isInside(x, y)) {
                picked = true;
                offsetX = x - b.getX();
                offsetY = y - b.getY();
                stretching = false;
                activeBalloon = b;

            } else if (b.isOnBorder(x, y)) {
                picked = true;
                offsetR = b.distance(x, y) - b.getRadius();
                stretching = true;
                activeBalloon = b;
            }
        }
        if (picked)
            repaint();
    }
...
}

在Balloon()类的子类之一SquareBalloon()中,我有以下内容:

 public class SquareBalloon extends Balloon implements MouseListener{
    public SquareBalloon() {
    }

    /**
     * Constructs a balloon with a given center, radius and color
     * 
     * @param x
     *            x-coordinate of the center
     * @param y
     *            y-coordinate of the center
     * @param r
     *            radius of the balloon
     * @param c
     *            color of the balloon
     */
    public SquareBalloon(int x, int y, int r, Color c) {
        super(x, y, r, c);
    }

    /**
     * Draws a solid circle if makeItFilled is true and outline only if
     * makeItFilled is false
     * 
     * @param g
     *            graphics context
     * @param makeItFilled
     *            draws a solid circle if true
     * @param rotate
     *            receives rotate variable value set in mousePressed() method of 
     *            DrawingPanel() class
     */
    public void draw(Graphics g, boolean makeItFilled, int rotate) {
        Graphics2D g2d = (Graphics2D) g;
        g.setColor(color);
        System.out.println("This is the value of rotate" + rotate + "from the draw() method of SquareBalloon() class.");
        if (makeItFilled) {
            Rectangle rect2 = new Rectangle(xCenter - radius, yCenter - radius, radius, radius);
            if (rotate == 1) {
                System.out.println("This is the value of rotate" + rotate
                        + "from the makedItFilled if statement in draw() method of SquareBalloon() class.");
                g2d.rotate(45* (Math.PI/180));              
            }
            g2d.fill(rect2);

        } else {
            Rectangle rect2 = new Rectangle(xCenter - radius, yCenter - radius, radius, radius);
            if (rotate == 1) {
                System.out.println("This is the value of rotate" + rotate
                        + "from the other if statement in draw() method of SquareBalloon() class.");
                g2d.rotate(45 * (Math.PI/180));
            }
            g2d.draw(rect2);

        }
    }


}