我正在尝试使用JFrame
制作计算器。创建5个以上的按钮后,JPanel
不会显示任何内容。这是我的代码:
JFrame:
package graphics;
import java.awt.*;
import javax.swing.*;
public class Driver01 {
public static void main(String[] args) {
JFrame frame = new JFrame("Basic Calculator");
frame.setContentPane(new Panel01());
frame.setSize(400, 500);
frame.setLocation(850, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(new Panel01());
frame.setAlwaysOnTop(true);
}
}
和JPanel:
package graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class Panel01 extends JPanel {
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0;
GridBagConstraints gbc = new GridBagConstraints();
public Panel01() {
setLayout(new GridBagLayout());
b1 = new JButton("1");
gbc.gridx = 2;
gbc.gridy = 2;
add(b1, gbc);
b2 = new JButton("2");
gbc.gridx = 3;
gbc.gridy = 2;
add(b2, gbc);
b3 = new JButton("3");
gbc.gridx = 4;
gbc.gridy = 2;
add(b3, gbc);
b4 = new JButton("4");
gbc.gridx = 2;
gbc.gridy = 3;
add(b4, gbc);
b5 = new JButton("5");
gbc.gridx = 3;
gbc.gridy = 3;
add(b5, gbc);
// b6 = new JButton("6");
// gbc.gridx = 4;
// gbc.gridy = 3;
// add(b6, gbc);
// b7 = new JButton("7");
// gbc.gridx = 2;
// gbc.gridy = 4;
// add(b7, gbc);
// b8 = new JButton("8");
// gbc.gridx = 3;
// gbc.gridy = 4;
// add(b8, gbc);
// b9 = new JButton("9");
// gbc.gridx = 4;
// gbc.gridy = 4;
// add(b9, gbc);
// b0 = new JButton("0");
// gbc.gridx = 2;
// gbc.gridy = 5;
// add(b0, gbc);
}
}
当我注释掉最后5个按钮时,我可以看到前5个按钮。
5个按钮
无
答案 0 :(得分:0)
只需更改
即可 frame.setContentPane(new Panel01());
到
Panel01 p1 = new Panel01();
frame.setContentPane(p1);
我不确定为什么会有效,但重要的是可行!