gpt4 book ai didi

Java GridBagLayout - 禁用垂直填充

转载 作者:行者123 更新时间:2023-11-29 07:47:38 24 4
gpt4 key购买 nike

我在 GridBagLayout-GUI 中遇到垂直填充问题。这是代码:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class Spielklasse {

public static void main(String[] args) {

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

for (int i = 0; i < 5; i++) {
JPanel subPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel();
label.setText("label " + i + ":");
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(120,20));

subPanel.add(label, BorderLayout.WEST);
subPanel.add(textField, BorderLayout.EAST);

GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTHWEST;
c.gridx = 1;
c.gridy = i;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(10, 20, 10, 20);
c.fill = GridBagConstraints.HORIZONTAL;
page.add(subPanel, c);
}

JScrollPane scrollPane = new JScrollPane(page);

JFrame frame = new JFrame();
frame.setSize(300,500);
frame.add(scrollPane);
frame.setVisible(true);
}
}

我想在前面的标签下面直接放置标签+文本字段,而不填充它们之间的垂直空间(就像当您垂直调整我的示例大小时直到您可以看到垂直滚动条)。我怎样才能做到这一点?使用我的代码,整个面板都是垂直填充的,但我不希望这样。

最佳答案

删除下一行c.weighty = 1;

阅读更多 docs .

编辑:在循环后使用虚拟 JLabel 获取可用空间:

GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
c.fill = GridBagConstraints.BOTH;
c.weightx=1;
c.weighty=1;
c.gridwidth = 2;
page.add(new JLabel(" "),c);

关于Java GridBagLayout - 禁用垂直填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24121806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com