繁体   English   中英

在Java中将变量从一个类获取到另一个

[英]Getting variables from one class to another in java

我正在尝试获取correct的变量,该变量包含Window类中的actionPerformed方法到Display类中的方法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")
        {

        }
    }
}

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM