0

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, enter image description here When really, the area that the same code with a JButton takes up is more like this: enter image description here 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?

Joehot200
  • 1,070
  • 15
  • 44
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal, Complete, Verifiable Example). 2) One way to get images for an example is to hot-link to images listed in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Sep 11 '14 at 11:51
  • 1
    @AndrewThompson Either someone knows the answer or they do not. Since that is the only code relevant, I do not understand the point of putting in code that would work in the IDE. No idea what your second link is going on about :/. – Joehot200 Sep 11 '14 at 11:54
  • *"Since that is the only code relevant.."* Famous last words. But if by 'relevant' you mean code I or others can copy/paste, compile and test (which is what is relevant to me, as a potential helper) then, no it is not all the relevant code.. – Andrew Thompson Sep 11 '14 at 11:57

2 Answers2

3

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)
    }
});
Martin Frank
  • 3,445
  • 1
  • 27
  • 47
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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Hey! Many thanks for that! The other answer was great, but that StretchIcon is so much easier. However, it is not quite stretching it sideways. Any way to fix that? http://gyazo.com/437111079ae300dd0309127b8b914a5c.png – Joehot200 Sep 12 '14 at 10:17
  • @Joehot200, you can configure the class to stretch proportionally (the default) or to stretch to fill the space. You need to use a different constructor if you want to fill the space. – camickr Sep 12 '14 at 13:59
  • can I just be stupid and ask you to show me where the code it so make it stretch to fill the space? – Joehot200 Sep 12 '14 at 14:10
  • 1
    @Joehot200, you can use any of the constructors with a `proportionate` parameter can be set to `false`. I'm assuming you are using the constructor that passes an `Image` to the StretchIcon, so you just add `false` as the second parameter. `ie. public StretchIcon(Image image, boolean proportionate)` – camickr Sep 12 '14 at 14:46