gpt4 book ai didi

java - 将顶部与 JPanel 中新行中的每个元素垂直对齐

转载 作者:行者123 更新时间:2023-12-01 18:33:54 25 4
gpt4 key购买 nike

我有一个 JPanel,面板中包含一组其他 JPanel(每个 JPanel 都包含一个 JLabel)。如何设置面板,使内部 JPanel 与 JPanel 的顶部垂直对齐,并且每个内部面板进入新行。喜欢:

InnerPanel 1
InnerPanel 2
InnerPanel 3


// empty space

我尝试不设置布局(使用默认布局),但内部面板位于同一行,直到该行被填满。喜欢:

InnerPanel 1 InnerPanel 2 InnerPanel 3
InnerPanel 4



// empty space

我还尝试过 BoxLayout 和 GridBagLayout,但内部面板空间占用了面板的整个垂直空间,如下所示:

InnerPanel 1


InnerPanel 2


InnerPanel 3

代码:

public class HomeStream extends JPanel
public HomeStream()
{
this.setLayout(new GridBagLayout());
int counter = 0;

// HomeStreamContent is the inner panel here containing a JLabel
for (HomeStreamContent hsc : this.content)
{
this.add(hsc, getConstraints(0, counter++));
}
}

public static GridBagConstraints getConstraints(int x, int y)
{
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.weightx = 1.0;
c.weighty = 0.1;
c.insets = new Insets(10, 10, 10, 10);
c.anchor = GridBagConstraints.PAGE_START;
c.fill = GridBagConstraints.HORIZONTAL;

return c;
}

最佳答案

使用BoxLayout,您需要将面板的maximumSize设置为preferredSize,因为如果您所以对于每个内部面板,您都可以这样做

JPanel panel = new JPanel() {
@Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
};
<小时/>

enter image description here

import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TestBoxLayout {

public TestBoxLayout() {
Box box = Box.createVerticalBox();
for (int i = 1; i < 4; i++) {
JPanel panel = new JPanel() {
@Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
};
JLabel label1 = new JLabel("Label");
JLabel label2 = new JLabel(String.valueOf(i));
panel.add(label1);
panel.add(label2);
box.add(panel);

}

JFrame frame = new JFrame();
frame.add(box);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args) {
new TestBoxLayout();
}
}
<小时/>

不设置最大值

enter image description here

导入javax.swing.Box;

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

public class TestBoxLayout {

public TestBoxLayout() {
Box box = Box.createVerticalBox();
for (int i = 1; i < 4; i++) {
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Label");
JLabel label2 = new JLabel(String.valueOf(i));
panel.add(label1);
panel.add(label2);
box.add(panel);
}

JFrame frame = new JFrame();
frame.add(box);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args) {
new TestBoxLayout();
}
}

关于java - 将顶部与 JPanel 中新行中的每个元素垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22904353/

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