Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

java - JMenuItem ImageIcon too big

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...