如何使用流布局删除JPanel之间的填充?

这是我的Java应用程序GUI的一部分,我有一个问题。

在此处输入图像描述

这个GUI包含的是一个蓝色的JPanel(容器),默认的FlowLayout作为LayoutManager,它包含一个Box,它包含两个JPanels(用于删除水平间距,或者我可以使用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之间的垂直填充?

我知道这是填充因为我读到了边距和填充之间的差异? “padding =元素从文本到边框周围(内部)的空间。”

这不起作用,因为这必须与组件之间的间隙(空间) 有关.-如何在MigLayout中删除JPanel填充?

我试过这个,但它也没用。 Java中的JPanel Padding

您可以在FlowLayout 设置间隙 ,即

 FlowLayout layout = (FlowLayout)southPanel.getLayout(); layout.setVgap(0); 

默认的FlowLayout具有5个单位的水平和垂直间隙。 在这种情况下,水平无关紧要,因为BorderLayout正在水平拉伸面板。

或者使用新的FlowLayout简单地初始化面板。 这将是相同的结果。

 new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); 

编辑:

“我试过了,没用……”

对我有用……

在此处输入图像描述在此处输入图像描述

设置间隙↑不设置间隙↑

 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(); } }); } } 

注意:始终发布一个可运行的示例(正如我所做的那样)以获得更好的帮助。 你说它不起作用,但它总是适用于我,所以如果没有一些代码可以运行并certificate问题,我们怎么知道你做错了什么?