java - 获取似乎从另一个类分层的内容

标签 java swing

我正在尝试制作一个简单的 GUI 文字拖动游戏,我构建代码的方式是我有一个 Driver 类,它设置主 JFrame 和一个 JPanel(其中包含单词)和一个提示的 JButton一个 Popup 类,用于请求添加新单词。然后创建一个WordBox。我的问题似乎是由于 Popup 类是一个子类(我认为这是正确的术语)这一事实引起的,因此似乎有一个额外的 Popup 类作为 Driver 和实际 Popup 之间的一层字框。我知道这很令人困惑,但这里是一些代码:

public class Popup extends JFrame implements ActionListener {

JLabel lblPrompt;
JTextField txtWord;
JButton btnOK;
BoxWord w;
static BoxWord word;


public Popup(){
    //window formatting was here

    btnOK.addActionListener(this);
} 

@Override
public void actionPerformed(ActionEvent e){
    w = new BoxWord(txtWord.getText());
    //word = new BoxWord("it works");
}

public static void main(String[] args) {
    Popup p = new Popup();
    //System.out.println(word.getWord());
}

public class BoxWord extends JButton {

private String s = "";

public BoxWord(String word){
    this.s = word;
    this.setText(word);
}

public String getWord(){
    return s;
}
}

和驱动程序:

公共(public)类 Driver 扩展 JFrame 实现 ActionListener{

JButton addWord;
JPanel panel;
int x, y;

public Driver(){
    //Window formatting was here


    addWord.addActionListener(this);

} 

public static void main(String[] args) {
    Driver d = new Driver();
}
@Override 
public void actionPerformed(ActionEvent e){//make a new popup to ask for word
    Popup p = new Popup();
    BoxWord w = p.w;
    System.out.println(w.getWord());
    w.setLocation(100,100);
}

我的错误是(至少是它的开头。整个事情大概有 20 行长):

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at worddrag.Driver.actionPerformed(Driver.java:42)

第 42 行是

System.out.println(w.getWord());

我觉得这是一个非常微不足道和简单的问题,但我不明白为什么我不断收到错误。我本质上需要能够从 Popup main 方法访问 Popup actionPerformed 方法中的 BoxWord。感谢任何和所有的帮助。我对文字墙表示歉意

最佳答案

当您尝试访问它时,

w 显然为空。

您的问题是您使用的是 JFrame,其中模式对话框或 JOptionPane 效果会更好。如果您使用了对话框,那么您的调用代码将等待直到对话框不再可见,那时 w 可能不再为空。


编辑
你问:

and can you elaborate on why JFrame will not work? Just telling me that its my problem doesnt help very much -

什么?我不只是告诉你这是问题所在——我提供了一个解决方案——使用模态 JDialog。 再次,模式对话框在启动时将卡住调用代码的代码流,并且调用代码将保持卡住状态,直到对话框不再可见。

您的问题是您尝试在对话框窗口有机会对其执行任何操作之前使用 w 变量。 JFrame 不会暂停调用代码的程序流,这导致了您的问题。


编辑2

So a JFrame doesn't actually execute the code until it is closed?

不,根本不是这样。查看在 JFrame 按钮的 ActionListener 中为您的 w 提供了有效引用的位置。因此,在调用 ActionListener 之前,w 不会收到有效的引用,这仅在按下按钮时才会发生。您编写的代码尝试在用户有机会按下弹出窗口的按钮之前立即使用 w 。如果您使用模态 JDialog,并确保在关闭对话框之前设置了 w,您的代码就可以工作。

But a JDialog will do so as it gets the input?

不。见上文。

关于java - 获取似乎从另一个类分层的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22160353/

相关文章:

java - 减少 opengl es 中锯齿现象的最佳方法? (图像调整大小)

java - 如何获取 Java JAR 文件中资源的路径

java - 定制 JTable 外观

用于绘制图像的 Java Graphics2D 方法,其中使用像素 alpha 值,但颜色值替换为给定颜色

java - 从 JList 中删除多个选择

java - java 上的 KeyAdapter、awt、swing 运行时错误。帮助发现错误

java - 使用 HQL 更新时预计会出现 StaleObjectStateException

java - WordUtils.capitalizeFully 是 I18N 吗?

java - Azure ClearDB : Access denied for user 'xxxx' to database 'xxxx'

java - 更改java中不同类的标签文本