java - GridBag 面板不占用所有空间

标签 java swing user-interface

我正在尝试创建一个在列中带有标签的行列表。我正在尝试使用 gridbaglayout,但遇到了问题。当我展开窗口时,它不会展开。发生的情况是这样的: enter image description here

我真正想要的是布局中的单元格占据 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);
     }

最佳答案

我相信问题出在你的体重计算上......

double weight = 1/(lables.length);

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

相反,尝试类似...

double weight = 1d/(double)lables.length;

关于java - GridBag 面板不占用所有空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16268319/

相关文章:

java - 为什么 Swing 创建者创建了 mouseDragged 方法?

java - 如何在 Java 中设置千位分隔符?

java - 调用 setVisible(false) 后,调用 set Visible(true) 时我的 JFrame 内容消失了

java - 我的自定义 Log4j2 XML 配置文件 Java 中的记录时间不正确

java - 格式化 JTextPane

java - 在 JFrame 中键入会出现错误

user-interface - 带分割栏的 Javafx BorderPane

Java GUI 不一致

python - 如何将事件绑定(bind)到 Canvas 项目?

user-interface - 在 Unity 中从像素坐标转换为 UI 坐标