【问题标题】:GridLayout hgap vgap "not working" on JPanel?GridLayout hgap vgap在JPanel上“不起作用”?
【发布时间】:2014-02-06 19:09:47
【问题描述】:
    JPanel grid = new JPanel();
    GridLayout layout = new GridLayout (6,7,0,0);
    grid.setLayout (layout);

    slot = new ImageIcon ("");

    for (int x = 0; x < 42; ++x)
    {
        slotbtn = new JButton(slot);
        slotbtn.setContentAreaFilled (false);
        //slotbtn.setBorderPainted (false);
        slotbtn.setBorder (BorderFactory.createEmptyBorder (0,0,0,0));
        slotbtn.setFocusPainted (false);
        grid.add(slotbtn);
    }

这是我得到的输出:

我正在创建一个 6x7 网格。我需要的输出是行和列之间没有空格,所有内容都应该压缩在一起。我试过打包,但没有用。我究竟做错了什么?

-- 我尝试了 FlowLayout,但我不得不调整框架的大小,并且框架上还有其他按钮,所以我不认为我更愿意调整它的大小以使按钮适合它们的位置。 -- 我把这个 JPanel 放在另一个 jpanel 中(它使用borderlayout 并包含另外两个面板),我把它放在中心,另外两个面板北和南。

【问题讨论】:

  • 感谢所有回答的人,我现在可以正常工作了。真的感谢你的努力,我会投票给每个人的答案

标签: java swing


【解决方案1】:

这个问题是因为你将grid(网格的整个大小)划分为7*6,所以如果你重新调整窗口大小,你会看到这个间隙发生了变化,所以如果你不想删除这个噱头

  1. 计算窗口大小(例如:width = 7* width of your image , hight = 6*hight of your mage)
  2. 或调整图片大小

【讨论】:

  • 如果我要调整图像大小,我怎么知道它应该有多大?
  • 你所说的“多大”是什么意思?您将固定网格大小,然后为其获取宽度和高度,然后将宽度/7和高度/6(或您想要的任何值)相除,将图像调整为新的,但如果图像太小它会造成失真,如果它太大,则需要一些时间
  • 我在谈论调整图像大小以使其适合按钮,因为您建议我调整图像大小。我刚决定调整框架的大小,我想我现在可以接受了
【解决方案2】:

JButton 使用margin 属性为按钮的内容区域提供额外的填充,您可以尝试使用...

slotbtn.setMargin(new Insets(0, 0, 0, 0));

我也会尝试使用slotbtn.setBorder(new LineBorder(Color.RED)); 之类的东西来确定间距是来自按钮、图标还是布局

GridLayout 还将根据容器的可用空间为每个单元格提供等量的空间,这意味着单元格可能会增加超过图标的大小。

虽然需要做更多工作,但GridBagLayout 将(如果配置正确)尊重每个组件的首选大小。

查看How to use GridBagLayout 了解更多想法。

【讨论】:

    【解决方案3】:

    使用您的代码,我使用 any 图像没有任何边距。检查您的图像。并且可能发布一个可运行的示例来复制问题。也许有些事情你没有向我们展示。我首先检查图像的边距。对照此检查。如果它仍然有边距,那么它就是你的图像。另外,不要将大小设置为任何值!您可能会不必要地拉伸面板,这会造成间隙。此外,如果您的其他面板中的一个比握把面板大,它也会导致它拉伸。但是把你的set(Xxx)sizes all 拿出来看看会发生什么。就pack()

    import java.awt.GridLayout;
    import javax.swing.*;
    
    public class TestButtonGrid {
    
        public TestButtonGrid() {
    
            ImageIcon icon = new ImageIcon(getClass().getResource("/resources/stackoverflow3.png"));
            JPanel panel = new JPanel(new GridLayout(6, 7));
    
            for (int i = 0; i < 42; i++) {
                JButton slotbtn = new JButton(icon);
                slotbtn.setContentAreaFilled(false);
                //slotbtn.setBorderPainted (false);
                slotbtn.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
                slotbtn.setFocusPainted(false);
                panel.add(slotbtn);
            }
    
            JFrame frame = new JFrame();
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
    
        }
    
        public static void main(String[] args) {
            new TestButtonGrid();
        }
    }
    

    【讨论】:

    • 哇,感谢您的回答和我现在修复它的努力,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多