按钮的返回方法不起作用

时间:2012-08-26 14:29:40

标签: java netbeans

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);
        }
    });
}
}

当我运行程序时,我收到此错误

enter image description here

2 个答案:

答案 0 :(得分: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);
        }
    });
}

答案 1 :(得分:1)

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

static JPanel panel;

所以当你去添加它时:

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

它抛出一个NPE。