添加按钮时java swing空指针异常
所以我试图做一个java-swing-gui 用于学校项目,因此我必须向 JPanel 元素添加 72 个按钮 (idk)。 我尝试使用 for 循环:
for (JButton btn : btns) {
panel.add(btn);
}
但它并没有真正起作用并引发了 nullPointerException。 有什么建议吗?
这是完整的代码:
import javax.swing.*;
import javax.swing.plaf.DimensionUIResource;
import java.awt.*;
public class mädn extends JFrame{
static JPanel panel = new JPanel();
static JFrame frame = new JFrame();
static JButton[] fields = new JButton[72];
public static void main(String[] args) {
new mädn();
}
public mädn() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new DimensionUIResource(500, 500));
frame.setTitle("Mensch Ärger Dich Nicht");
panel.setLayout(new GridLayout(11, 11));
panel.setBackground(Color.blue);
for (JButton field : fields) {
field.setSize(20, 20);
panel.add(field);
}
frame.add(panel);
frame.setVisible(true);
}
}
So i was trying to do a java-swing-gui for a school project and therefor I have to add 72 Buttons (idk) to a JPanel element.
I tried using a for-loop:
for (JButton btn : btns) {
panel.add(btn);
}
but it didnt really work out and threw a nullPointerExeption.
Any suggestions?
Here is the full code:
import javax.swing.*;
import javax.swing.plaf.DimensionUIResource;
import java.awt.*;
public class mädn extends JFrame{
static JPanel panel = new JPanel();
static JFrame frame = new JFrame();
static JButton[] fields = new JButton[72];
public static void main(String[] args) {
new mädn();
}
public mädn() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new DimensionUIResource(500, 500));
frame.setTitle("Mensch Ärger Dich Nicht");
panel.setLayout(new GridLayout(11, 11));
panel.setBackground(Color.blue);
for (JButton field : fields) {
field.setSize(20, 20);
panel.add(field);
}
frame.add(panel);
frame.setVisible(true);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您创建这样的数组时:
该数组是空的。换句话说,即使该数组有能力保留 72 个按钮,但它还没有这些按钮,您必须手动添加它们,如下所示:
但如果不这样做,
fields[i]< /code> 默认情况下将为
null
,因此当您尝试执行field.setSize(20, 20)
时,该字段为 null 并会导致空指针异常
。原始数组也有默认值。例如,
int
数组的元素均为0
,boolean
数组的元素均为false
。对于非原始数组(例如JButton
)也是如此,元素默认都是null
。您的最终代码将如下所示:
或:
甚至更短:
还可以考虑将
72
转换为常量(static final
字段)。When you create an array like this:
that array is empty. In other words, even though that array has the capacity to keep 72 buttons, it doesn't have those buttons yet, you have to add them manually, like this:
But if you don't,
fields[i]
will benull
by default, and so when you try to dofield.setSize(20, 20)
, that field is null and will cause aNullPointerException
.Primitive arrays also have default values. For example elements of an array of
int
are all0
, and elements of an array ofboolean
are allfalse
. The same is true for non-primitive arrays (likeJButton
), the elements are all by defaultnull
.Your final code would look something like this:
or:
or even shorter:
Also consider turning that
72
into a constant (astatic final
field).