Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JButton with padding between its border and the button itself

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?

like image 876
user2896152 Avatar asked May 14 '15 13:05

user2896152


1 Answers

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

enter image description here

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.

like image 195
user1803551 Avatar answered Oct 06 '22 00:10

user1803551