我在同一个包中有两个类。我已经宣布了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
那么它应该去另一个班级。
谢谢。
查看您的代码,您似乎想使用特定文本向用户显示对话框
gui.setTextArea(welcome());
gui.setTextArea(describe());
有时,该对话框应该捕获用户输入,然后进行处理。
- Those
setTextArea
调用不是您想要使用的。用户永远不会看到欢迎消息,因为它会立即被描述消息替换。
- 确保您没有阻止事件调度线程 (EDT),否则将不会显示任何内容。我不知道你的是什么
Command
类就可以了,但是我看到了无限循环Event Dispatch Thread
这绝不是一件好事。看看Swing 中的并发教程 http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html了解更多信息
- 多亏了这一点
for
循环时,用户将无法输入任何命令,因为 EDT 正忙于处理循环。您需要的是一个允许用户提供输入的阻塞调用(不阻塞 EDT,而只是阻塞代码的执行)。中的静态方法JOptionPane http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html类非常适合这个(例如JOptionPane#showInputDialog
)。这些方法还具有一种机制,可以将用户输入传递回调用代码,而无需任何静态变量,这可以解决您的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)