【问题标题】:Getting variables from one class to another in java在java中从一个类到另一个类获取变量
【发布时间】:2017-01-19 16:15:54
【问题描述】:

我正在尝试获取变量correct,其中包含从Window 类中的方法actionPerformedDisplay 类中的方法paint 的信息。我不知道该怎么做,因为Window 类在调用时也需要 3 个 int 值。

public class Window extends JFrame implements ActionListener
{

    /**
     * Constructor for Window
     */
    public Window(int width, int height, int gridSize)
    {
        //save instance variables:
        WIDTH = width;
        HEIGHT = height;
        this.gridSize = gridSize;
    }

    public void actionPerformed(ActionEvent e)
    {
        int moveCode;
        int direction;
        Words guess = new Words();

        if(e.getActionCommand().equals("button"))  //button has been pressed
        {
            //get entered values from textfields:
            String num = numField.getText();
            String dir = ltrField.getText();
            String word = wordField.getText();
            String correct;

            //convert to number:
            int numberWord = Integer.parseInt(num) - 1;

            //convert "A" or "D" to 0 or 1:
            if(dir == "A")
            {
                direction = 0;
            }
            else
            {
                direction = 1;
            }

            if(guess.words[numberWord][direction].equals(word))
            {
                correct = word;
            }
            else
            {
                correct = "No";
            }
        }
    }
}

public class Display extends JPanel
{
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g); //clear the old drawings
        final int PAD = 20;      //extra space so field isn't right at edges
        if(correct == "Java")
        {

        }
    }
}

【问题讨论】:

  • 我只是在这里猜测,但 9/10 次窗口对象将在您的超类中创建(您在其中调用 paintComponent)。从那里获取窗口并添加一个 getter 方法。

标签: java class variables methods


【解决方案1】:

String correct; 变量在public void actionPerformed(ActionEvent e) 内部定义,这使其成为局部变量。局部变量“存在”在方法内部,并且在该方法之外不可用。您可以做的是在Window 类级别将correct 定义为实例变量

class Window {
    private String correct; 
    public String getCorrect() { 
        return correct;
    }
}

以后你可以像这样在Display 类中使用它:

Window window = getWindow();
String correct = window.getCorrect();

【讨论】:

  • 它说它“找不到符号 - 方法 getWindow()”。这是因为我使用的是 BlueJ 吗?
  • @HiMyNameIsW 你需要定义这样的方法。或者您可以将窗口对象作为附加参数传递给 public void paintComponent(Graphics g) 方法。
  • 我试过这个“Window window = new Window(25,25,25);”我知道这行不通,因为它已经制作好了,但我不知道还能做什么。
猜你喜欢
  • 2013-10-04
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多