JButton with padding between its border and the button itself

牧云@^-^@ 提交于 2019-12-22 13:05:13

问题


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 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?


回答1:


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.

Because if you read the documentation for setMargin you'll see that

[...] 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).

Also, reserve uppercase names for classes, rename JBtn to jBtn.




回答2:


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).

Instead, you can use a CompoundBorder, for example...

JBtn.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(Color.CYAN, 5), 
        BorderFactory.createEmptyBorder(5, 5, 10, 10)));


来源:https://stackoverflow.com/questions/30239318/jbutton-with-padding-between-its-border-and-the-button-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!