0

stackoverflow 上的某个人帮助我处理了这段代码,所以我可以在一个方法中使用它来返回我点击的按钮......现在 netbeans 没有显示任何冲突的代码,但是当我运行它时,它会给出错误

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public final class CharSearch extends Box{
int i =0;
int error = 0;
static JPanel panel;
String original = "Dinosaur";
JLabel label = new JLabel();
String secret = new String(new char[original.length()]).replace('\0', '-');

public CharSearch(){

super(BoxLayout.Y_AXIS);
    for(char i = 'A'; i <= 'Z'; i++){
        String buttonText = new Character(i).toString();
        JButton button = getButton(buttonText);
        add(button);
    }
}

public JButton getButton(final String text){
    final JButton button = new JButton(text);
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "You have clicked: "+text);
            //If you want to do something with the button:
            button.setText("Clicked"); // (can access button because it's marked as final)
        }
    });
    return button;
}

public static void main(String[] args){
    EventQueue.invokeLater(new Runnable(){
        public void run(){
           JFrame frame=new JFrame();
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
        }
    });
}
}

当我运行程序时出现此错误

在此处输入图像描述

4

2 回答 2

1

很明显,您永远不会初始化静态属性面板:

static JPanel panel;

所以在这部分代码中生成了NPE:

public static void main(String[] args){
    EventQueue.invokeLater(new Runnable(){
        public void run(){
           JFrame frame=new JFrame();
            frame.add(panel); // <--------------- NullPointer to panel
            frame.pack();
            frame.setVisible(true);
        }
    });
}
于 2012-08-26T14:35:17.413 回答
1

您已panel声明但从未实例化:

static JPanel panel;

所以当你去添加它时:

JFrame frame = new JFrame();
frame.add(panel);

它抛出一个 NPE。

于 2012-08-26T14:35:22.240 回答