【问题标题】:GridBagLayout TroubleshootingGridBagLayout 疑难解答
【发布时间】:2015-07-08 05:08:15
【问题描述】:

所以我决定让我的 GUI 看起来更好一些,并改用 GridBagLayout。以下是我要添加到面板中的对象:

choosePanel = new JPanel();
choosePanel.setLayout(new GridBagLayout());

chooseLabel = new JLabel("Choose a quarter to input data for:");
addItem(chooseLabel, 0, 0, 1, 1);

qGroup = new ButtonGroup();

    q1 = new JRadioButton("Q1");
    qGroup.add(q1);
    q1.setSelected(true);
    addItem(chooseLabel, 0, 1, 1, 1);

    q2 = new JRadioButton("Q2");
    qGroup.add(q2);
    addItem(chooseLabel, 0, 2, 1, 1);

    q3 = new JRadioButton("Q3");
    qGroup.add(q3);
    addItem(chooseLabel, 0, 3, 1, 1);

    q4 = new JRadioButton("Q4");
    qGroup.add(q4);
    addItem(chooseLabel, 0, 4, 1, 1);

chooseButton = new JButton("Press to Enter Quarter");
    chooseButton.addActionListener(e->{
        cl.show(mainPanel, "Info");
        this.setSize(330, 240);
    });
    chooseButton.setPreferredSize(new Dimension(200, 100));
    addItem(chooseLabel, 1, 1, 1, 1);

    resetButton = new JButton("Reset all previous data");
    resetButton.addActionListener(e->{

    });
    resetButton.setPreferredSize(new Dimension(200, 100));
    addItem(chooseLabel, 1, 2, 1, 1);

这里是“addItem”方法:

private void addItem(JComponent c, int x, int y, int width, int height){
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = width;
    gbc.gridheight = height;
    gbc.weightx = 100.0;
    gbc.weighty = 100.0;
    gbc.fill = GridBagConstraints.NONE;
    choosePanel.add(c, gbc);
}

我的问题是,当我运行程序时,只显示屏幕中间的选择标签,没有别的。有人知道怎么修这个东西吗? ......

【问题讨论】:

  • 如果您可以发布我们可以运行的代码,这将更容易修复.. 但是addItem(chooseLabel, 0, 4, 1, 1);,您一直在添加chooseLabel..
  • 我从未感到如此愚蠢。让我尝试修复它,如果它不起作用,我将发布整个代码:)

标签: java swing user-interface layout-manager gridbaglayout


【解决方案1】:

改变

q1 = new JRadioButton("Q1");
qGroup.add(q1);
q1.setSelected(true);
addItem(chooseLabel, 0, 1, 1, 1);

q2 = new JRadioButton("Q2");
qGroup.add(q2);
addItem(chooseLabel, 0, 2, 1, 1);

q3 = new JRadioButton("Q3");
qGroup.add(q3);
addItem(chooseLabel, 0, 3, 1, 1);

q4 = new JRadioButton("Q4");
qGroup.add(q4);
addItem(chooseLabel, 0, 4, 1, 1);

到

q1 = new JRadioButton("Q1");
qGroup.add(q1);
q1.setSelected(true);
addItem(q1 , 0, 1, 1, 1);

q2 = new JRadioButton("Q2");
qGroup.add(q2);
addItem(q2, 0, 2, 1, 1);

q3 = new JRadioButton("Q3");
qGroup.add(q3);
addItem(q3, 0, 3, 1, 1);

q4 = new JRadioButton("Q4");
qGroup.add(q4);
addItem(q4, 0, 4, 1, 1);

等等..你一直在添加chooseLabel。

【讨论】:

  • 在使用复制粘贴的时候真的要多加注意。我想我应该多一点耐心;)
  • @WyattLowery 是的,当发生这种“奇怪”的事情时,最好再次通读您的代码!哦,好吧,我相信每个人以前都经历过类似的事情。 :)
  • 如果它有助于解决问题,请accept the answer。
猜你喜欢
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
  • 2014-08-29
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多