在actionPerformed
中,似乎根據Eclipse,所有變量(submit,msg,input)「無法解析」。根據我的經驗(其中我很少),這意味着我沒有定義變量。但是,正如你在代碼中看到的那樣,我已經定義了它們。 Submit是一個JButton,msg是一個字符串,輸入是一個JTextField。Java將無法識別已定義的變量?
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);
}
}
}
我知道我的一些進口是不必要的。
附言:我正在做一個小的文字冒險遊戲,我的德國類
縮進你的代碼三立,請,這是很難說的事情的範圍應該是。 – millimoose
對不起。我將來會記住這一點。同時,你有解決我的問題嗎? – user2426434
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html。您應該閱讀本教程,注意實例變量(字段)和局部變量(方法中定義的變量)之間的差異。特別是讀取部分:「*局部變量只對聲明它們的方法可見;它們不能從其他類訪問*」 –