我正在尝试将包含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")
{
}
}
}
答案 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();