14

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?

Balder
  • 8,623
  • 4
  • 39
  • 61
Roman
  • 124,451
  • 167
  • 349
  • 456

5 Answers5

14
Border emptyBorder = BorderFactory.createEmptyBorder();
yourButton.setBorder(emptyBorder);

For more details on borders see the BorderFactory

Eric Eijkelenboom
  • 6,943
  • 2
  • 25
  • 29
12
yourButton.setBorderPainted(false);
user-id-14900042
  • 686
  • 4
  • 17
Anonymous
  • 121
  • 1
  • 2
7

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);
Stig Helmer
  • 103
  • 1
  • 5
3

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!

Carl Smotricz
  • 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
1

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:

enter image description here

Buttons with border painted set to false removes the border and hover action but keeps the padding:

button.setBorderPainted(false);

enter image description here

Buttons with a null border or empty border removes the border, hover action and padding:

button.setBorder(BorderFactory.createEmptyBorder());

or

button.setBorder(null);

enter image description here

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

enter image description here

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

enter image description here

The.Laughing.Man
  • 479
  • 4
  • 11