[英]return method for buttons don't work
Someone on stackoverflow helped me with this code so I can use it in a method to return the button I clicked... Now netbeans doesn't show any conflicting code, but when i run it, it gives errors 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);
}
});
}
}
When I run the program I get this error 当我运行程序时,我收到此错误
Farily obvious, you never initialize the static atribute panel: 很明显,你永远不会初始化静态属性面板:
static JPanel panel;
So the NPE is generated in this part of the code: 所以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);
}
});
}
You have panel
declared but it is never instantiated: 您已声明了
panel
但它从未实例化:
static JPanel panel;
so when you go to add it: 所以当你去添加它:
JFrame frame = new JFrame();
frame.add(panel);
it throws a NPE. 它抛出一个NPE。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.