【问题标题】:Outer class unable to access a method's local variable外部类无法访问方法的局部变量
【发布时间】:2018-05-05 00:21:46
【问题描述】:

我正在使用 paintComponent 方法在 JPanel 中绘制不同的形状,并计算每种形状(即矩形和椭圆形)的迭代次数。我希望我的实例变量能够访问在paintComponent方法中递增的这个形状计数变量,但无法弄清楚为什么实例变量“countRectangle1”没有复制方法的局部变量“countRectangle”--

package ch8ex8p1;

import java.security.SecureRandom;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;

public class DrawShape extends JPanel
{
private SecureRandom randomNumbers = new SecureRandom();
private int x;
private int y;
private int width;
private int height;
private Color color;
private int countRectangle1; //this will copy countRectangle after iteration 
private int countOval1;


public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    int width = getWidth(); //total width
    int height = getHeight(); //total height
    int coordinate1;
    int coordinate2;
    int countRectangle = 0; //counts number of times a Rectangle is drawn


    for (int counter = 0; counter <=10; counter++ )
    {
        //generate numbers to use for x and width
        coordinate1 = randomNumbers.nextInt(width);
        coordinate2 = randomNumbers.nextInt(width);

        while (coordinate1 == coordinate2)
            coordinate2 = randomNumbers.nextInt(width);

        //identify x and width
        if (coordinate1 > coordinate2)
        {
            this.width = coordinate1;
            this.x = coordinate2;
        }
        else
        {
            this.width = coordinate2;
            this.x = coordinate1;
        }

        //generate numbers to use for y and height
        coordinate1 = randomNumbers.nextInt(height);
        coordinate2 = randomNumbers.nextInt(height);
        while (coordinate1 == coordinate2)
            coordinate2 = randomNumbers.nextInt(height);

        //identify y and height
        if (coordinate1 > coordinate2)
        {
            this.height = coordinate1;
            this.y = coordinate2;
        }
        else
        {
            this.height = coordinate2;
            this.y = coordinate1;
        }

        //generate random color for the shapes
        Color color = new Color(randomNumbers.nextInt(256), randomNumbers.nextInt(256),
                randomNumbers.nextInt(256));
        this.color = color;

        setBackground(Color.BLACK);

        //draw random shape
        int drawFlag = randomNumbers.nextInt(2);
        if (drawFlag==0)
        {
            MyRect myRectangle = new MyRect(this.x, this.y, this.width, this.height
                    , this.color);
            myRectangle.draw(g);
            setCount(1);
            countRectangle++;
        }
        else
        {
            MyOval myOval = new MyOval(this.x, this.y, this.width, this.height
                    , this.color);
            myOval.draw(g);

        }

    }//end for loop


    //assign count to outer variable
    this.countRectangle1 = countRectangle;
    //setCount(countRectangle);
    System.out.print("\ncount Rectangle: " + countRectangle1);

}//end painComponent

public void setCount(int count)
{
    countRectangle1 = countRectangle1 + count;
}

public int getCount()
{
    return countRectangle1;
}
}//end class

我尝试过使用 setter 和 getter,但它不起作用。我也尝试将类的变量更改为“受保护”,但它仍然不起作用。似乎当paintComponent完成时,计数重置回0。我在分配值时将“this”添加到类变量中,但它仍然没有得到正确的输出。在paintComponent中,它似乎得到了计数,但是当它在paintComponent之外时,它变成了0。

这是调用计数的类,但得到的是 0:

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.*;

public class DrawShapeTest extends JFrame 
{
public static void main(String[] args)
{
    DrawShape shape = new DrawShape();
    JFrame app = new JFrame();
    app.setSize(400, 400);

    JLabel rectangleLabel = new JLabel();
    //rectangleLabel.setText("aaaarrrrrgghhhh!!!!!" + shape.getCount());
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    shape.setSize(300, 300);
    System.out.println("\nsecond print Rectangle: " + shape.getCount());
    app.setLayout(new BorderLayout());
    app.add(shape);
    app.add(rectangleLabel, BorderLayout.SOUTH);
    app.setVisible(true);
}
}

感谢任何帮助。 Rectangle 计数的假定第二个打印行显示为 0,实际上是在 Draw Shape Class (生成形状的地方)下的 for 循环之前打印,所以我的代码似乎乱序,我目前仍在尝试想办法。

【问题讨论】:

  • "... 在内部类中 ..." - 我没有看到任何内部类,既不是静态的,也不是非静态的,也不是匿名的。总而言之,我很难理解你想要达到的目标。您拥有属性 countRectangle1 和局部变量 countRectangle 的事实也无济于事。你能改写你的解释吗?还有什么“不起作用”是什么意思?你的尝试没有编译吗?他们扔了Exceptions 吗?请准确。
  • @Turing85 您好,感谢您的回复。我实际上是指方法而不是内部类,我很抱歉。我还编辑了我的描述。实例变量 countRectangle1 没有获得paintComponent 中的迭代次数,被paintComponent 的局部变量countRectangle 捕获。
  • 请提供您访问countRectangle1的代码。我很确定您的 System.out.print("\ncount Rectangle: " + countRectangle1); 打印正确的值
  • @MạnhQuyếtNguyễn 感谢您的回复。我在顶部添加了代码,并更新了问题描述。看来我的代码乱序了,我还在摸索中。

标签: java


【解决方案1】:

app.setVisible(true);之后调用System.out.println("\nsecond print Rectangle: " + shape.getCount());

问题是您在分配变量值之前访问该变量,因为函数paintComponent() 在开始绘制之前不会运行。 (可见)

编辑 要启动 JFrame 应用程序,请将其放入您的 main 方法中

java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
           JFrame frame = new JFrame();
             //bla bla....
           frame.setVisible(true);
      }
});

【讨论】:

  • 谢谢,但它会产生相同的输出:/
  • 这句话System.out.print("\ncount Rectangle: " + countRectangle1);打印出来什么东西吗?
  • 我认为它不会打印任何东西,因为你还没有启动你的应用程序
  • 它确实打印了.. 输出是 >>second print Rectangle: 2 >>first count Rectangle: 5 >>first count Rectangle: 7 看起来第二个打印行首先执行,据说是在调用paintComponent 方法之后。即使我在 setvisible 或将面板添加到框架之后移动第二个打印行,它仍然是第一位的
  • 我删除了所有迭代以简化代码,似乎访问变量的行为是相同的。 JFrame 类上的 System.out 打印行首先出现..
猜你喜欢
  • 1970-01-01
  • 2020-07-30
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
相关资源
最近更新 更多