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?
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
.
精彩评论