[英]return method for buttons don't work
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);
}
});
}
}
當我運行程序時,我收到此錯誤
很明顯,你永遠不會初始化靜態屬性面板:
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);
}
});
}
您已聲明了panel
但它從未實例化:
static JPanel panel;
所以當你去添加它:
JFrame frame = new JFrame();
frame.add(panel);
它拋出一個NPE。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.