0

I have a JFrame and an ImageIcon as a JLabel that I want to appear fully off of the JFrame.

Code:

JFrame frame = new JFrame("test");
frame.setSize(1000, 1000);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

try {
    BufferedImage bf = ImageIO.read(new File(FILEPATH));
    img = new JLabel(new ImageIcon(bf));
} catch (IOException e) {
    e.printStackTrace();
}

frame.getContentPane().add(img);
img.setBorder(new EmptyBorder(0, frame.getContentPane().getWidth(), 0, 0));

This code only makes the JLabel/image appear half off of the screen. I can easily fix it by setting the left parameter of the EmptyBorder to frame.getContentPane.getWidth() * 2, but I am just wondering why it seems to cut the inset distance in half. From my testing, only cuts it in half if the JLabel contains an ImageIcon. If it contains text, the insets work as they seem like they should. I have only tested with text and ImageIcon.

Caders117
  • 319
  • 3
  • 18
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Try to replicate the problem without the image. If that is not possible, one way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Dec 02 '17 at 03:26
  • I did a quick test with your code and I don't have any issues - but, I added the `JLabel` (with no image) to the frame before it was made visible and called `revalidate` on the `contentPane` AFTER the border was set – MadProgrammer Dec 02 '17 at 05:17
  • `but, I added the JLabel (with no image)` - the OP already stated it wasn't a problem with text and I confirmed that as well with my answer. The revalidate isn't the issue either. Swing invokes revalidate() and repaint() when you set a property of the component. – camickr Dec 02 '17 at 05:46

1 Answers1

1

Not sure what the exact calculation is, but by default the Icon is centered in the space available.

As you noticed it appears that when only the Icon is displayed the Icon appears to be moved to the left by half the size of the Icon.

This does not happen if you have both an Icon and text (or just text).

One solution is:

img = new JLabel(new ImageIcon(bf), SwingConstants.LEFT);
camickr
  • 321,443
  • 19
  • 166
  • 288