下面是我有问题的java应用程序GUI的一部分。

这个图形用户界面包含一个蓝色的JPanel(容器),默认的FlowLayout是LayoutManager,它包含一个包含两个JPanels的盒子(去掉水平间距,或者我可以使用setHgaps为零,而不是一个盒子),每个盒子都包含一个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(蓝色的)和盒子之间的垂直填充?
我知道这是填充,因为我在Difference between margin and padding?上读到“填充=从文本到边框的元素周围(内部)的空间。”
这将不起作用,因为这必须是由于组件之间的间隙(空格)。- How to remove JPanel padding in MigLayout?
我试过了,但也不起作用。JPanel Padding in Java
发布于 2014-12-08 08:41:49
您可以只在FlowLayout中使用set the gaps,即
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();
}
});
}
}注意:为了获得更好的帮助,请始终发布一个可运行的示例(就像我所做的那样)。你说它不工作,但它总是对我有效,那么如果没有一些运行和演示问题的代码,我们怎么知道你做错了什么呢?
https://stackoverflow.com/questions/27348665
复制相似问题