1

我得到了另一个问题,该问题将转到“Java noobs”类别
这次我的问题如下:
我需要人能够单击按钮,它会显示 JOptionPane。但是,一旦我单击按钮,它就会给我例外。

我的按钮:

    inputChar = new JButton("Guess Letter");
    add(inputChar);
    this.add(Box.createVerticalStrut(10));
    inputChar.setAlignmentX(Component.CENTER_ALIGNMENT);
    inputChar.addActionListener(this);



public void actionPerformed(ActionEvent e) {

    String action = e.getActionCommand();

    if (action == "Guess Letter"){
        gl.getChar();
    }   

现在我的 getChar() 方法在不同的类中,如下所示:

public String getChar(){
    inChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
    if (inChar.length() > 1){
        JOptionPane.showMessageDialog(null, "Your Input is incorred, please input char", "Input warning", JOptionPane.WARNING_MESSAGE);
    }
    return inChar;
}

异常触发上线gl.getChar();

例外情况如下:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Interface.ButtonPanel$1.actionPerformed(ButtonPanel.java:34)

任何想法如何解决它?

编辑注:

我设法用 Loagans 小费解决了这个问题。基本上在 GuessedLetters 类中,我只设置构造函数 setter/getter,在动作监听器中,我放入设置它们的方法。

使用以下 ActionListener 解决了问题:

    if (action == "Guess Letter"){
        inputChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
        if (inputChar.length() > 1){
            JOptionPane.showMessageDialog(null, "Your Input is incorred, please input char", "Input warning", JOptionPane.WARNING_MESSAGE);
        }else{
        GuessedLetters glr = new GuessedLetters(inputChar);
        glr.setInChar(inputChar);
        //For testing purposes
        System.out.println(glr.getInChar());
        }
4

1 回答 1

1

看起来您的主类可能正在扩展另一个类,因为您可以调用 this.actionPerfomed。这意味着对主类的任何操作都会触发该方法。相反,您应该做的是将 actionListener 添加到您的特定按钮。

您需要更改操作 == 比较以使用 String .equals 方法,因为您正在比较字符串值。那 == 可能会在启动时触发窗口,因为这两个值都是空的,所以它可能会显示带有空指针异常的窗口?

然后,您将如何将动作侦听器添加到用户按下的特定按钮。

    viewInsertFileButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(final java.awt.event.ActionEvent evt) {
            displayJOptionPaneHere();
        }
    });

因此,您只想显示 JOptionPane 并在该特定按钮上执行操作,而不是在主应用程序上执行任何 actionPerformed。

我认为这是导致空指针异常的原因。

 if (inChar.length() > 1){

在调用它之前,请检查 inChar != null 是否。您可以将代码包装在其中,因此它仅在开始时不为 null 时才调用 if (inChar.length() > 1。这是我一直遇到的常见问题,在 null 上调用方法目的。

将其更改为这样,您的异常应该消失。

public String getChar(){
    inChar = JOptionPane.showInputDialog("Please enter letter (a-z)");
    if (inChar != null) {
       if (inChar.length() > 1){
           JOptionPane.showMessageDialog(null, "Your Input is incorred, please input char", "Input warning", JOptionPane.WARNING_MESSAGE);
       }
     } else {
          inChar = ""
     }

    return inChar;
}

你也可以在这里保护 gl 不为空。

if (gl == null) {
   gl = new gl();
}

    gl.getChar();
于 2012-08-11T18:51:51.753 回答