如何调整 JButton 的大小以适合图标?

问题描述 投票:0回答:2

我试图制作我的大学网站的用户界面,但遇到了一个问题,按钮周围有一个奇怪的边框

这就是现在的样子:

它应该是这样的:

public static void middleBar(JFrame frame){
        JPanel middle = new JPanel();
        middle.setLayout(new GridLayout(4,6,20,20));
        String[] items = {"UniversityERP","Award","Blackboard","CCT","CertificateIssuance","CourseEvaluationSurvey","DoctoralPortal",
        "Fastrack","HostelManagement","IDCardManagement","MobileAppCMS","OnCampusJob","StudentOutboundMobility","StudentAttendanceRecording","StudentAttendanceManagement",
        "StudentClearance","StudentPaymentCenter"};
        for(String item:items){
            ImageIcon icon = new ImageIcon("Images/"+item+".png");
            JButton button = new JButton(icon);
            Dimension d = new Dimension(icon.getIconWidth(),icon.getIconHeight());
            button.setPreferredSize(d);
            middle.add(button);
        }
        JPanel middleBar = new JPanel(new BorderLayout());
        middleBar.add(middle,BorderLayout.NORTH);
        frame.add(middleBar,BorderLayout.CENTER);
    }

如何删除它?

我尝试使用 setPreferedSize 方法,但没有成功

java swing user-interface awt
2个回答
1
投票

正如 gthanop 所提到的,使用时应将边距设置为零。

但仅供参考,什么是保证金? 边距很容易理解,但它是(任何内容)内容与边框之间的间隙。边距采用

Insets
来定义此偏移量。这是其给出的方式 在文档中

java.awt.Insets.Insets(int top, int left, int bottom, int right)


Creates and initializes a new Insets object with the specified top, left, bottom, and right insets.
Parameters:
top - the inset from the top.
left - the inset from the left.
bottom - the inset from the bottom.
right - the inset from the right.

让我们看一个例子

我这里有一个很酷的小按钮。我还没有修改边距。

这里我将边距插入修改为顶部= 1,底部= 10,右侧= 10,左侧= 10。

这是所有插图均为零的情况,当您使用类似的图像时会更明显

然而,这并没有完全删除边框,并在外面留下一条小线,这是按钮的边框,它不是我们现在需要的,所以我们可以继续删除它。

button.setBorder(null);

或使用替代方案

Border emptyBorder = BorderFactory.createEmptyBorder();
button.setBorder(emptyBorder);

这里我们删除按钮的默认边框,因为我们不需要它

cool shi6

最终应该是这样的。

这将删除边框并使图像覆盖整个按钮,并且按钮将完美运行。


0
投票

我认为这可能是 GridLayout 拉伸按钮以适应网格单元。您可能最好使用 GridBagLayout 甚至更好的 MigLayout 来更好地控制组件的布局

© www.soinside.com 2019 - 2024. All rights reserved.