icon on jlabel get the size of the jlabel
I'm using a Jlabel with an icon in swing. I chose an image from my computer as the icon and I can't find a way to make it resize automatically to the size of the Jlabel. Because the image I want is much bigger then the size of the Jlabel i'm only seeing a small part of it. Is there any way to solve this problem so I won't need to resize each image before importing it to the project?
Might be your LayoutManger
/lack there of thats interfering as JLabel
should return correct size according to the content displayed.
Please post SSCCE to show specific problems.
Though regardless a large image will still need to be scaled, here is a nice method I usually use:
public static BufferedImage scaleImage(int w, int h, BufferedImage img) throws Exception {
BufferedImage bi;
bi = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(img, 0, 0, w, h, null);
g2d.dispose();
return bi;
}
here is an example:
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}
private void initComponents() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage img = null;
try {
BufferedImage tmp = ImageIO.read(new URL("http://photos.appleinsider.com/12.08.30-Java.jpg"));
img = scaleImage(200, 200, tmp);
} catch (Exception ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(new ImageIcon((Image) img));
frame.add(label);
frame.pack();
frame.setVisible(true);
}
public static BufferedImage scaleImage(int w, int h, BufferedImage img) throws Exception {
BufferedImage bi;
bi = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(img, 0, 0, w, h, null);
g2d.dispose();
return bi;
}
}
链接地址: http://www.djcxy.com/p/67660.html
上一篇: 在JLabel中对齐文本和图标的方式不同