gpt4 book ai didi

java - JPanel 布局管理器 - 如何防止组件填充空间?

转载 作者:行者123 更新时间:2023-12-04 00:22:27 26 4
gpt4 key购买 nike

我正在尝试构建一组两个标签和一个按钮(label-button-label),看起来像下面的第一行:

enter image description here .

我正在努力使用 Java Swing 来做到这一点。我尝试过使用 BorderLayout、BorderLayout.WEST、BorderLayout.CENTER、BorderLayout.EAST 但这会使按钮填满空间: enter image description here

这是我为此使用的代码:

panel = new JPanel(new BorderLayout());
l1 = new JLabel("l1");
button = new JButton("B");
l2 = new JLabel("l2");
panel.add(l1, BorderLayout.WEST);
panel.add(button, BorderLayout.CENTER);
panel.add(l2, BorderLayout.EAST);

我也尝试过 GridBagLayout,我最接近的是让它们间隔开,但不要紧靠两侧:

enter image description here

代码:

panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
l1 = new JLabel("L1");
l2 = new JLabel("L2");
button = new JButton("B");
c.weightx = Integer.MAX_VALUE;
c.gridx = 0;
panel.add(l1, c);
c.weightx = 1;
c.gridx = 1;
panel.add(button, c);
c.weightx = Integer.MAX_VALUE;
c.gridx = 2;
panel.add(l2, c);

有什么想法吗?

最佳答案

这里有两种方法。一次使用 BorderLayout,一次使用 GridBagLayout:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

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

public class TestGridBagLayout {

protected void initUI1() {
final JFrame frame = new JFrame("Grid bag layout");
frame.setTitle(TestGridBagLayout.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel l1 = new JLabel("L1");
JLabel l2 = new JLabel("L2");
JButton b = new JButton("B");
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
panel.add(l1, gbc);
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(b, gbc);
gbc.weightx = 0;
panel.add(l2, gbc);
frame.add(panel);
frame.setSize(800, 100);
frame.setVisible(true);
}

protected void initUI2() {
final JFrame frame = new JFrame("Border layout");
frame.setTitle(TestGridBagLayout.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JLabel l1 = new JLabel("L1");
JLabel l2 = new JLabel("L2");
JButton b = new JButton("B");
JPanel wrappingPanel = new JPanel(new FlowLayout());
wrappingPanel.add(b);
panel.add(l1, BorderLayout.WEST);
panel.add(l2, BorderLayout.EAST);
panel.add(wrappingPanel);
frame.add(panel);
frame.setLocation(0, 125);
frame.setSize(800, 100);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TestGridBagLayout test = new TestGridBagLayout();
test.initUI1();
test.initUI2();
}
});
}

}

关于java - JPanel 布局管理器 - 如何防止组件填充空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14501396/

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