Java 如何去除按钮周围的边框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2713190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove border around buttons?
提问by Roman
I have a JPanel with the GridLayout. 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?
我有一个带有 GridLayout 的 JPanel。在网格的每个单元格中,我都有一个按钮。我看到每个按钮都被灰色边框包围。我想删除这些边框。有谁知道如何做到这一点?
回答by Carl Smotricz
I think it's very likely the borders are part of the buttons' GUI. You could try calling .setBorder(null)
on all the buttons and see what happens!
我认为边框很可能是按钮 GUI 的一部分。您可以尝试调用.setBorder(null)
所有按钮,看看会发生什么!
回答by Eric Eijkelenboom
Border emptyBorder = BorderFactory.createEmptyBorder();
yourButton.setBorder(emptyBorder);
For more details on borders see the BorderFactory
有关边框的更多详细信息,请参阅BorderFactory
回答by Anonymous
yourButton.setBorderPainted(false);
yourButton.setBorderPainted(false);
回答by Stepan
It can be like this:
它可以是这样的:
yourButton.setBorder(null);
回答by Stig Helmer
In most recent Java versions it's necessary to call setContentAreaFilled(false) to remove the border entirely. Add an empty border for some padding:
在最新的 Java 版本中,需要调用 setContentAreaFilled(false) 来完全删除边框。为一些填充添加一个空边框:
button.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
button.setContentAreaFilled(false);
回答by The.Laughing.Man
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);
}
});