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?
5 Answers
Border emptyBorder = BorderFactory.createEmptyBorder();
yourButton.setBorder(emptyBorder);
For more details on borders see the BorderFactory

- 6,943
- 2
- 25
- 29
In most recent Java versions it's necessary to call setContentAreaFilled(false) to remove the border entirely. Add an empty border for some padding:
button.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
button.setContentAreaFilled(false);

- 103
- 1
- 5
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!

- 66,391
- 18
- 125
- 167
-
If you are correct in your assumption (seems reasonable to me), that would adversely affect useability. Those borders are there partly to show which button has the input focus. – Andrew Thompson Jul 14 '11 at 07:28
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:
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);
}
});

- 479
- 4
- 11