Java无法识别已定义的变量?
在actionPerformed
中,似乎所有变量(submit、msg、input)都无法根据Eclipse进行解析。根据我的经验(我几乎没有经验),这意味着我没有定义变量。但是,正如你在代码中看到的,我已经定义了它们。Submit是一个JButton,msg是一个字符串,input是一个JTextField
package levels;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.*;
public class LevelOne extends JFrame implements ActionListener{
private Object msg;
public void one(){
setTitle("Conjugator");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("images/LevelOneBG.gif")));
setLayout(new FlowLayout());
JTextArea area = new JTextArea("You enter a castle. A Goblin demands you correct his sentences!");
add(area);
setVisible(true);
//these aren't being called to actionPerformed
JButton submit = new JButton("Check sentence");
submit.addActionListener(this);
setVisible(true);
JTextField input = new JTextField("Ich spielen Golf.");
input.setActionCommand("input");
add(input);
input.addActionListener(this);
setVisible(true);
String msg = ("Test successful");
}
//this should be successfully locating and utilizing "submit", "input" and "msg", but it won't
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submit) {
msg = submit.getText();
//!! Display msg only **after** the user has pressed enter.
input.setText(msg);
}
}
}
我知道我的一些进口商品是不必要的
另外,我正在为我的德语课做一个小的文本冒险游戏
# 1 楼答案
这些变量的作用域仅为one()方法。如果你想让全班同学都能看到,就把它们放在最上面的味精旁边
# 2 楼答案
变量
submit
在方法one()
中定义为局部变量它在方法
actionPerformed()
中不可用