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

时间:2017-01-19 16:15:54

标签: java class variables methods

我正在尝试将包含correct类中方法actionPerformed的信息的变量Window添加到paint中的方法Display类。我无法弄清楚如何做到这一点,因为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")
        {

        }
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

以后可以在Display类中使用它,如下所示:

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