0

I'm trying to set up a few JLabels to use as buttons inside a BoxLayout, stacked on top of each other. The layout is fine, but I'm finding that I can't resize the labels to the dimensions I want. I'm using the following code to size them:

JLabel fileAddBtn = new JLabel("Add File", SwingConstants.CENTER);
fileAddBtn.setBorder(BorderFactory.createLineBorder(Color.black));
fileAddBtn.setMaximumSize(new Dimension(Integer.MAX_VALUE, fileAddBtn.getMinimumSize().height));

and

    JLabel fileRemBtn = new JLabel("Remove File", SwingConstants.CENTER);
fileRemBtn.setBorder(BorderFactory.createLineBorder(Color.black));
fileRemBtn.setMaximumSize(new Dimension(Integer.MAX_VALUE, fileRemBtn.getMinimumSize().height));

As of now I have two labels, with one being longer than the other. They are both taking the width of the longer label, which is good, but the labels are hugging the edges of the text right to the nearest pixel. Is there any way to make the labels a little bigger so that there is a bit of a border around the labels? I've tried using setSize() but it doesn't take. I've also added straight values into the above code, but it doesn't change them either. I tried adding an EmptyBorder() around them, which worked for sizing, but it hid my line border which surrounds them. Any thoughts?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3226170
  • 175
  • 1
  • 1
  • 14

1 Answers1

2

Is there any way to make the labels a little bigger so that there is a bit of a border around the labels?

Sure. Add an EmptyBorder.

But since the code is already adding a border to the labels, to retain that line border, make a CompoundBorder consisting of the empty border and the line border, and set the compound border to the label.

See also Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (Yes.)

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433