这是我有疑问的 Java 应用程序 GUI 部分。
这个 GUI 包含一个蓝色的 JPanel(容器),默认 FlowLayout 作为 LayoutManager,它包含一个包含两个 JPanel 的 Box(以删除水平间距,或者我可以使用 setHgaps 为零而不是一个 Box)它每个都包含一个 JLabel。
这是我创建该部分 GUI 的代码。
private void setupSouth() {
final JPanel southPanel = new JPanel();
southPanel.setBackground(Color.BLUE);
final JPanel innerPanel1 = new JPanel();
innerPanel1.setBackground(Color.ORANGE);
innerPanel1.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
innerPanel1.add(new JLabel("Good"));
final JPanel innerPanel2 = new JPanel();
innerPanel2.setBackground(Color.RED);
innerPanel2.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
innerPanel2.add(new JLabel("Luck!"));
final Box southBox = new Box(BoxLayout.LINE_AXIS);
southBox.add(innerPanel1);
southBox.add(innerPanel2);
myFrame.add(southPanel, BorderLayout.SOUTH);
}
我的问题是如何摆脱外部 JPanel(蓝色)和 Box 之间的垂直填充?
我知道这是填充,因为我在 Difference between margin and padding? 上阅读过“填充 = 元素周围(内部)从文本到边框的空间。”
这是行不通的,因为这必须归因于组件之间的间隙(空间)。- How to remove JPanel padding in MigLayout?
我试过了,但也没用。 JPanel Padding in Java
最佳答案
你可以 set the gaps在 FlowLayout
中,即
FlowLayout layout = (FlowLayout)southPanel.getLayout();
layout.setVgap(0);
默认的 FlowLayout
有 5 个单位的水平和垂直间距。在这种情况下水平无关紧要,因为 BorderLayout
水平拉伸(stretch)面板。
或者使用新的 FlowLayout
简单地初始化面板。这将是相同的结果。
new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
编辑:
"I tried that, didn't work.."
对我有用...
设置间隙 ↑ 不设置间隙 ↑
import java.awt.*;
import javax.swing.*;
public class Test {
public void init() {
final JPanel southPanel = new JPanel();
FlowLayout layout = (FlowLayout)southPanel.getLayout();
layout.setVgap(0);
southPanel.setBackground(Color.BLUE);
final JPanel innerPanel1 = new JPanel();
innerPanel1.setBackground(Color.ORANGE);
innerPanel1.add(new JLabel("Good"));
final JPanel innerPanel2 = new JPanel();
innerPanel2.setBackground(Color.RED);
innerPanel2.add(new JLabel("Luck!"));
final Box southBox = new Box(BoxLayout.LINE_AXIS);
southBox.add(innerPanel1);
southBox.add(innerPanel2);
southPanel.add(southBox); // <=== You're also missing this
JFrame myFrame = new JFrame();
JPanel center = new JPanel();
center.setBackground(Color.yellow);
myFrame.add(center);
myFrame.add(southPanel, BorderLayout.SOUTH);
myFrame.setSize(150, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationByPlatform(true);
myFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Test().init();
}
});
}
}
注意:始终发布一个可运行的示例(正如我所做的)以获得更好的帮助。你说它不起作用,但它总是对我有用,所以如果没有一些可以运行并演示问题的代码,我们怎么知道你做错了什么?
关于java - 如何删除仍然使用流布局的 JPanel 之间的填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348665/