简体   繁体   English

如何去除按钮周围的边框?

[英]How to remove border around buttons?

I have a JPanel with the GridLayout.我有一个带有 GridLayout 的 JPanel。 In every cell of the grid I have a button.在网格的每个单元格中,我都有一个按钮。 I see that every button is surrounded by a gray border.我看到每个按钮都被灰色边框包围。 I would like to remove these borders.我想删除这些边框。 Does anybody know how it can be done?有人知道怎么做吗?

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

For more details on borders see the BorderFactory有关边框的更多详细信息,请参阅BorderFactory

yourButton.setBorderPainted(false);

In most recent Java versions it's necessary to call setContentAreaFilled(false) to remove the border entirely.在最新的 Java 版本中,需要调用 setContentAreaFilled(false) 来完全移除边框。 Add an empty border for some padding:为一些填充添加一个空边框:

button.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
button.setContentAreaFilled(false);

I think it's very likely the borders are part of the buttons' GUI.我认为边框很可能是按钮 GUI 的一部分。 You could try calling .setBorder(null) on all the buttons and see what happens!您可以尝试在所有按钮上调用.setBorder(null)看看会发生什么!

它可以是这样的:

yourButton.setBorder(null);

While all of these answers work in some way, I thought I'd provide a little more in depth comparison of each along with examples.虽然所有这些答案都以某种方式起作用,但我想我会提供一些更深入的比较以及示例。

First default buttons:第一个默认按钮:

在此处输入图像描述

Buttons with border painted set to false removes the border and hover action but keeps the padding:边框绘制设置为 false 的按钮将删除边框和悬停动作,但保留填充:

button.setBorderPainted(false);

在此处输入图像描述

Buttons with a null border or empty border removes the border, hover action and padding:带有空边框或空边框的按钮会移除边框、悬停动作和填充:

button.setBorder(BorderFactory.createEmptyBorder());

or或者

button.setBorder(null);

在此处输入图像描述

Buttons with an empty border plus dimensions removes the border and hover action and sets the padding to the provided values:具有空边框和尺寸的按钮会删除边框和悬停动作并将填充设置为提供的值:

border.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));

在此处输入图像描述

Lastly, combine these with a background and hover action to get custom matte buttons that get highlighted on hover:最后,将这些与背景和悬停动作相结合,以获得在悬停时突出显示的自定义遮罩按钮:

button.setBackground(Color.WHITE);
button.setBorderPainted(false);

button.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseEntered(java.awt.event.MouseEvent evt) {
        button.setBackground(Color.GRAY);
    }

    public void mouseExited(java.awt.event.MouseEvent evt) {
        button.setBackground(Color.WHITE);
    }
});

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM