I am new here.
I have a JLabel with a fixed size and an image in it placed with JLabel.CENTER. I wanted to know how does it place the image for example when the width of the image is 49px and the width of the label is 50px. does the pixel comes at first or at the end of the label.
here the image in the jLabel (the jLabel has a border) the real image
Thanks to those who will take time to read this
There is no guarantee of exactly how a JLabel’s icon will be centered when the number of surplus pixels is odd. You can observe the current behavior, of course, but there’s no guarantee a later Java version won’t do it differently.
If you want to be certain, you can create a subclass of JPanel, override the paintComponent
and getPreferredSize
methods, and draw the image yourself:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import javax.swing.JPanel;
public class ImagePanel
extends JPanel {
private static final long serialVersionUID = 1;
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
@Override
public Dimension getPreferredSize() {
Insets insets = getInsets();
Dimension size = new Dimension(
insets.left + insets.right, insets.top + insets.bottom);
if (image != null) {
int width = image.getWidth(this);
int height = image.getHeight(this);
size.width += Math.max(width, 0);
size.height += Math.max(height, 0);
}
return size;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int width = image.getWidth(this);
int height = image.getHeight(this);
if (width > 0 && height > 0) {
int widthDifference = getWidth() - width;
int x = widthDifference / 2;
if (widthDifference % 2 != 0) {
// If you want the extra space on the left:
//x++;
}
int y = (getHeight() - height) / 2;
g.drawImage(image, x, y, this);
}
}
}
}