Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMenuItem ImageIcon too big

Tags:

java

swing

I've encountered a problem. My image is too big so it enlarges the corresponding JMenuItem. I don't want to develop bicycles like

ImageIcon image = new ImageIcon(new ImageIcon("/home/template/img.jpg")
        .getImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT));

Is there any other way to accomplish that?

like image 351
OneMoreVladimir Avatar asked Aug 02 '11 18:08

OneMoreVladimir


1 Answers

If you don't want to scale the image in code (I presume that's what you mean in the question?), why not just make the source image that size to start with? The simplest solution is sometimes the best!

Also, getScaledInstance() is generally a bad idea. This explains why and gives better options for resizing the image. If you're using the image elsewhere, then it's worth reading up on that article and scaling it using a better technique (such as graphics.drawImage()). But if you're just using it in the menu, then resizing the source image is probably the best thing to do.

If you are going to resize:

BufferedImage image = ImageIO.read("img.jpg");
BufferedImage ret = new BufferedImage(32,32,BufferedImage.TYPE_RGB);
ret.getGraphics().drawImage(image,0,0,32,32,null);

Something like that should give you the image, you can then create your ImageIcon using ret.

like image 81
Michael Berry Avatar answered Sep 23 '22 06:09

Michael Berry