【发布时间】:2012-09-06 02:32:12
【问题描述】:
我在同一个包中有两个类。我已经在一个类中声明了static variable,并希望在另一个类中访问该变量。
这是我声明静态变量的代码
public class wampusGUI extends javax.swing.JFrame {
static String userCommand;
public wampusGUI() {
initComponents();
}
public void setTextArea(String text) {
displayTextArea.append(text);
}
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
userCommand = commandText.getText();
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
wampusGUI w = new wampusGUI();
w.setVisible(true);
Game g = new Game(w);
g.play();
}
});
}
}
这是我要访问变量的代码
public class Game {
private wampusGUI gui;
public Game(wampusGUI w) {
world = new World();
world.start();
gui = w;
}
public void play() {
gui.setTextArea(welcome());
gui.setTextArea(describe());
for (;;) {
String s = userCommand; // here value should come should
System.out.println(userCommand);
Command c = Command.create(s);
String r = c.perform(world);
// is game over?
if (r == null) {
break;
}
System.out.println(r);
}
System.out.println("Game over");
}
}
但是,我可以将第一类的变量作为参数传递。但问题是,当我运行程序时,值第一次变为空,这是我不想要的。我想当我在textfield 中输入值时,它应该转到另一个类。
谢谢。
【问题讨论】:
-
“值第一次变为空”是什么意思?基本上你应该改变你的设计——拥有一个全局变量真的不是一个好的解决方案。
-
我同意@jon。在用户有机会更改它之前,您的 String 不会有一个像样的价值。此外,对于 Swing 应用程序来说,for 循环也不是一个好的设计。我想知道您是否真的想使用侦听器来侦听用户更改 JTextField 的状态然后对此进行操作。也许您还想考虑使用 Swing Timer,但在我们了解更多关于您的程序及其应该做什么之前很难知道。
-
请告诉我们:你想用这段代码做什么?
-
我想要做的是,在第一个 GUI 文件中,当用户应该在
textarea中输入文本并按enter然后该值应该进入另一个类play() method并且将执行command class的命令