How can I force an ImageIcon to be a certain size?

≯℡__Kan透↙ 提交于 2019-12-11 19:59:10

问题


Currently, I use this code:

 public class Test extends JFrame {
static Test t = null;
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
              t =  new Test();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public static void addComponentsToPane(Container pane) {

    JButton button;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    ImageIcon icon;
        icon = new ImageIcon(System.getProperty("user.dir") + "/res/background.png");
    Image img = icon.getImage() ;  
      Image newimg = getScaledImage(img, frame.getWidth(), frame.getHeight()) ;  
      icon = new ImageIcon( newimg );
     JLabel background=new JLabel(icon);

        //frame.getContentPane().add(background);

        background.setLayout(new FlowLayout());

    c.fill = GridBagConstraints.HORIZONTAL;
    c.ipady = frame.getHeight() * 10;
    c.weightx = 0.0;
    c.gridwidth = 3;
    c.gridx = 0;
    c.gridy = 1;

    pane.add(background, c);


}
private static Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();
    return resizedImg;
}

private void createAndShowGUI() {
    frame = new JFrame("GridBagLayoutDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

static JFrame frame = null;

public Test() {

    createAndShowGUI();
    addComponentsToPane(frame.getContentPane()); 
    frame.pack();
    frame.setVisible(true);
    frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}

}

This works fine for buttons, but for some reason is not working for a JLabel with an image. How can I make this JLabel/Image fit to the size I would like?

The image is being really tiny at the moment,

When really, the area that the same code with a JButton takes up is more like this:

Also, it is possible for me to get the ImageIcon to be bigger than button 4 as well, which I also would like to avoid.

So how can I stretch/contract the image to fit the area I would like it to have?


回答1:


So how can I stretch/contract the image to fit the area I would like it to have?

Check out Darryl's Stretch Icon. The Icon is automatically painted at the size of the component.




回答2:


you can use the code snippet from http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/IconDemoProject/src/components/IconDemoApp.java to create a scaled image... (from http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html)

just measure you button and adjust the image size

/**
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 * Resizes an image using a Graphics2D object backed by a BufferedImage.
 * @param srcImg - source image to scale
 * @param w - desired width
 * @param h - desired height
 * @return - the new resized image
 */
private Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();        
    return resizedImg;
}

i want to pick up a point from MadProgammer on his hint about using scaledInstance: https://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

so how to measure a buttons size?

final Button b = new Button(); //create it on your custom way...
b.addComponentListener(new ComponentAdapter() {

    @Override
    public void componentResized(ComponentEvent e){
        int w = b.getWidth();
        int h = b.getHeight();            
        setIconSize(w,h); //TODO by yourself (sorry, if more help required please say so)
    }
});


来源:https://stackoverflow.com/questions/25786708/how-can-i-force-an-imageicon-to-be-a-certain-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!