简体   繁体   English

为什么我不能使用GridBagLayout在JPanel中创建超过5个按钮

[英]Why can't I create more than 5 buttons in JPanel using GridBagLayout

I am trying to make a calculator using JFrame . 我正在尝试使用JFrame制作计算器。 JPanel doesn't display anything after I create more than 5 buttons. 创建超过5个按钮后, JPanel不显示任何内容。 Here is my code: 这是我的代码:

JFrame: 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);

    }
}

And JPanel: 和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);
    }

}

I can see the first 5 buttons when I comment out the last 5. 当我注释掉后5个按钮时,我可以看到前5个按钮。

5 buttons 5个按钮

在此处输入图片说明

none 没有

在此处输入图片说明

Just change your 只要改变你的

frame.setContentPane(new Panel01());

to

Panel01 p1 = new Panel01();
frame.setContentPane(p1);

I am not sure why it works, but what is important is that it works ! 我不确定它为什么起作用,但是重要的是它起作用了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM