在 actionPerformed
中,根据 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);
}
}
}
我知道我的一些导入是不必要的。
P.S.,我正在为我的德语课制作一个小型文本冒险游戏
最佳答案
您在方法 one()
中将变量定义为本地变量。根据定义,局部变量是...局部的。它们仅在定义它们的 block 中可见。为了在 one()
和 actionPerformed()
中可见,它们应该被定义为类的字段。
另一种方法是使用 one()
方法中定义的匿名内部类来定义您的操作监听器,但考虑到您还不掌握变量,您最好保持匿名稍后再上课。 Swing 是一个复杂的框架,在使用 Swing 之前您可能应该做一些更基本的编程练习。
关于Java无法识别已定义的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801845/