如何在数组中创建 JPanel 并向其中添加 Jlabel?
我看过很多网站。如果没有面板,标签会正确显示,如果有面板,则会出现错误:
Exception in thread "main" java.lang.NullPointerException
那么我该怎么解决这个问题呢?
这是源代码:
JLabel button[] = new JLabel[100];
JPanel[] panel = new JPanel[100];
for (int i = 0; i < button.length; i++) {
a = a + 50;
if (a > 549) {
b = b + 50;
a = 50;
}
button[i] = new JLabel("hi");
frame.add(button[i]); //is this necessary?
button[i].setVisible(true); // is this necessary?
button[i].setSize(50,50);
panel[i].add(button[i]);
panel[i].setVisible(true);
panel[i].setBounds(a, b, 50, 50);
frame.add(panel[i]);
}
这有什么问题,我该如何修复它?如您所知,它应该有 100 个在 10 x 10 数组中打招呼的标签。 这是它的样子:
I've looked at many websites. Without the panels, the labels appear correctly, with the panels it give the the error:
Exception in thread "main" java.lang.NullPointerException
so what can I do to fix this?
here is the source code:
JLabel button[] = new JLabel[100];
JPanel[] panel = new JPanel[100];
for (int i = 0; i < button.length; i++) {
a = a + 50;
if (a > 549) {
b = b + 50;
a = 50;
}
button[i] = new JLabel("hi");
frame.add(button[i]); //is this necessary?
button[i].setVisible(true); // is this necessary?
button[i].setSize(50,50);
panel[i].add(button[i]);
panel[i].setVisible(true);
panel[i].setBounds(a, b, 50, 50);
frame.add(panel[i]);
}
Whats wrong with this, how can I fix it? just so you know, it should have 100 labels that say hi in a 10 by 10 array.
this is what it looks like:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建
JPanel
数组仅创建该数组。它不会创建任何JPanel
来填充数组。因此,数组中填充有null
。您必须为数组的每个元素创建一个 JPanel:此外,一个组件可能只有一个祖先。按钮必须添加到框架或面板,但不能同时添加到两者。如果您希望该按钮位于面板中,则必须将其添加到面板中。
默认情况下,组件是可见的(除了必须可见的框架或对话框等顶级组件)。您不需要调用
button.setVisible(true)
。您绝对应该学习使用布局管理器,而不是明确设置组件的大小和边界。这是获得美观、便携的 GUI 应用程序的唯一方法。阅读 http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
Creating an array of
JPanel
only creates the array. It doesn't create anyJPanel
to fill the array. The arrays is thus filled withnull
s. You must create a JPanel for each element of the array:Moreover, a component may only have one ancestor. The button must be added to the frame or to the panel, but not both. If you want the button in the panel, it must be added to the panel.
Components are visible by default (except top-level ones like frames or dialogs which must be made visible). You don't need to call
button.setVisible(true)
.You should definitely learn to use layout managers rather than setting the size and bounds of your components explicitely. That's the only way to have good-looking, portable GUI apps. Read http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
不要使用
frame.setLayout(null);
使用 frame.setLayout(new GridLayout(10,10,10,10));don't use
frame.setLayout(null);
use frame.setLayout(new GridLayout(10,10,10,10)); instead, for example