2012-08-26 33 views
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); 
     } 
    }); 
} 
} 

當我運行程序我得到這個錯誤

enter image description here

回答

1

Farily明顯,你永遠不會初始化靜態屬性附加傷害面板:

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

你聲明panel但它永遠不會實例:

static JPanel panel; 

所以當你去添加:

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

它拋出一個NPE。