0

我正在尝试制作一个列中带有标签的行列表。我正在尝试使用 gridbaglayout,但遇到了问题。当我展开窗口时,它不会展开。这就是发生的事情: 在此处输入图像描述

我真正想要的是布局中的单元格占据 1/5 的空间,标签移动到单元格的最左侧。

   public static JPanel createLayout(int rows) {
    JPanel product = new JPanel(new GridBagLayout());
    String[] lables = {"School", "Advanced #", "Novice #"};
    double weight = 1/(lables.length);
    for (int i = 0; i < rows; i++) {
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(3, 3, 3, 3);
        c.anchor = GridBagConstraints.WEST;
        c.gridx = i;
        c.weightx = weight;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.anchor = GridBagConstraints.NORTHWEST;
        for (int j = 0; j < lables.length; j++) {

            JLabel l = new JLabel(lables[j]);
            product.add(l, c);
        }
    }
    return product;
}

public static void main(String[] args) throws IOException {
    JFrame frame = new JFrame("Debate Calculator");
    JPanel debates = new JPanel();
    frame.add(createLayout(5), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
     }
4

1 回答 1

2

我相信问题在于您的体重计算...

double weight = 1/(lables.length);

因为1lables.length都是 int 值,Java 会自动将结果转换为 a int(即0)。

相反,尝试类似...

double weight = 1d/(double)lables.length;
于 2013-04-28T21:59:51.943 回答