【发布时间】:2021-10-21 00:07:57
【问题描述】:
我是编程初学者,我正在尝试创建一个计算器,大约 1 到 2 小时前我才开始,但我遇到了一个问题,所有JButton 控件都消失了。请帮忙,我已经尝试了这么久,我只是不知道我的代码有什么问题。
代码如下:
import javax.swing.;
import java.awt.;
import java.awt.event.*;
public class Main {
static void gui() {
JPanel p = new JPanel();
JFrame f = new JFrame("Calculator");
f.add(p);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("YEET");
f.pack();
f.setSize(1930, 1090);
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
p.setLayout(null);
b0.setBackground(new Color(156,207,245));
b1.setBackground(new Color(156,207,245));
b2.setBackground(new Color(156,207,245));
b3.setBackground(new Color(156,207,245));
b4.setBackground(new Color(156,207,245));
b5.setBackground(new Color(156,207,245));
b6.setBackground(new Color(156,207,245));
b7.setBackground(new Color(156,207,245));
b8.setBackground(new Color(156,207,245));
b9.setBackground(new Color(156,207,245));
p.add(b1);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(b7);
p.add(b8);
p.add(b9);
b0.setVisible(true);
b1.setVisible(true);
b2.setVisible(true);
b3.setVisible(true);
b4.setVisible(true);
b5.setVisible(true);
b6.setVisible(true);
b7.setVisible(true);
b8.setVisible(true);
b9.setVisible(true);
p.setVisible(true);
f.setVisible((true));
}
public static void main(String[] args) {
gui();
}
}
【问题讨论】:
-
好吧,你的问题开始了
f.setLayout(null); -
使用适当的布局管理器,请参阅 Laying Out Components Within a Container 上的 Swing 教程。此外,无需在所有
JButtons 上使用setVisible(true),因为它们通过添加到的框架/面板可见。
标签: java swing jframe jpanel jbutton