0

I was just wondering if there is some option or shortcut in Netbeans which can make my life easy! To resize an imageicon of a jlabel I know we have to write a lot of code to do that, Is there anything in Netbeans that does it automatically? If not... just a 'No' is enough for me. If yes how?

Note: I am making all this using Netbeans GUI Builder.

Daksh Shah
  • 2,997
  • 6
  • 37
  • 71
  • It's not a lot of code really, and I highly discourage the use of a GUI builder. They created bloated and highly unmanageable code for something that would take 2-4 weeks to learn maximum (in my opinion) when you really sit down and work with it. – Rogue Apr 08 '14 at 12:10
  • Did you want it to fill the screen? Like as the background? – Paul Samsotha Apr 08 '14 at 12:45
  • @peeskillet I wanted to do that too, but in this question no, i want to fit the image to the size of the label. And yah do tell me how to do that background thing – Daksh Shah Apr 08 '14 at 12:46

2 Answers2

1

You can always just paint the image

jLabel1 = new javax.swing.JLaBel() {
    java.awt.Image image;
    {
        image = new javax.swing.ImageIcon(...).getImage(); 
    }

    @Override
    protected void paintComponent(java.awt.Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }
};

I know you've been using Netbeans GUI Builder, so you can look at this answer for how to edit the auto-generated initialization code. You'll edit it to look like something like the above. By using getWidth() and getHeight(), you stretching the image to size of the label

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
1

ImageIcons take the size of the image they contain. Period. You can write a new Icon implementation (see below) that will paint the image at a different size, but the icon in a JLabel will not adjust its size according to the size of the JLabel: it's the other way around.

public class MyImageIcon implements Icon {
    private final BufferedImage image;
    private final int width;
    private final int height;

    public MyImageIcon(BufferedImage img, int width, int height) {
        this.image = img;
        this.width = width;
        this.height = height;
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.drawImage(image, x, y, width, height, c);
    }

    public int getIconWidth() {
        return width;
    }

    public int getIconHeight() {
        return height;
    }
}
Maurice Perry
  • 32,610
  • 9
  • 70
  • 97