java JButton 在其边框和按钮本身之间有填充
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30239318/
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
JButton with padding between its border and the button itself
提问by user2896152
I've a JButton that has its background green-colored and its border as a LineBorder. I would like to insert a space between the button and the border, a kind of padding. I've tried with setMargin(new Insets(x,y,t,z)) but it seems not working. This is my piece of code.
我有一个 JButton,其背景为绿色,边框为 LineBorder。我想在按钮和边框之间插入一个空格,一种填充。我试过 setMargin(new Insets(x,y,t,z)) 但它似乎不起作用。这是我的一段代码。
JButton JBtn=new JButton("sdfd");
JBtn.setBorder(BorderFactory.createLineBorder(Color.CYAN,5));
JBtn.setBackground(Color.GREEN);
JBtn.setMargin(new Insets(5,5,10,10));
Any advice?
有什么建议吗?
回答by user1803551
The borders are part of the button and clicking on them will click the button. You can set the background as green, then paint borders over the background:
边框是按钮的一部分,单击它们将单击按钮。您可以将背景设置为绿色,然后在背景上绘制边框:
jBtn.setBackground(Color.GREEN);
jBtn.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.CYAN, 5),
BorderFactory.createLineBorder(Color.BLACK, 20)));
I've tried with setMargin(new Insets(x,y,t,z)) but it seems not working.
我试过 setMargin(new Insets(x,y,t,z)) 但它似乎不起作用。
Because if you read the documentation for setMargin
you'll see that
因为如果你阅读文档,setMargin
你会看到
[...] if a non-default border is set on the button, it is that Border object's responsibility to create the appropriate margin space (else this property will effectively be ignored).
[...] 如果在按钮上设置了非默认边框,则 Border 对象有责任创建适当的边距空间(否则此属性将被有效地忽略)。
Also, reserve uppercase names for classes, rename JBtn
to jBtn
.
此外,为类保留大写名称,重命名JBtn
为jBtn
.
回答by MadProgrammer
The change to the Border
is changing the way the margins
work (they don't seem to be included in the decisions for determining the layout any more).
对 的更改Border
正在改变margins
工作方式(它们似乎不再包含在确定布局的决策中)。
Instead, you can use a CompoundBorder
, for example...
相反,您可以使用 a CompoundBorder
,例如...
JBtn.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.CYAN, 5),
BorderFactory.createEmptyBorder(5, 5, 10, 10)));