-2

I want to adjust the size of logo2.png so that it completely fits to the jFrame. Can anyone help me out?

jLabel2 = new javax.swing.JLabel();

jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Banking/logo2.png"))); // NOI18N

JDesktopPane.add(jLabel2);
jLabel2.setBounds(0, 0, 500, 290);
Leigh
  • 28,765
  • 10
  • 55
  • 103
codeViper
  • 1
  • 1
  • 4

3 Answers3

2

JLabel doesn't rescale it's content (ie the image), for that, you're going to have to get you hands a little dirty...

There are a number of ways to achieve this. Personally, I'd start with a custom component, which extends from something like JPanel which takes a base image and is capable of scaling and painting it.

Take a look at Performing Custom Painting and Painting in AWT and Swing for more details about performing custom painting.

Scaling an image is not as straightforward as it might seem, while Java does provide some APIs to scale images, generally, they don't generate fantastic results. Take a look at Quality of Image after resize very low -- Java and The Perils of Image.getScaledInstance() for more details.

I would normally recommend taking a look at the imgscalr library, as it's results are generally quite good (better then what the base Java API provides or I've seen through most other methods), but for this example, I've included an example of a divide an conqure approach.

This example provides a "scale to fill" implementation, this ensures that the resulting image ALWAYS fills the available space while maintaining it's aspect ratio, see Java: maintaining aspect ratio of JPanel background image for more discussions on the subject

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ScaledBackground {

    public static void main(String[] args) {
        new ScaledBackground();
    }

    public ScaledBackground() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                try {
                    BufferedImage img = ImageIO.read(...);

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new ImagePane(img));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

    public class ImagePane extends JPanel {

        private BufferedImage original;
        private BufferedImage scaled;

        public ImagePane(BufferedImage img) {
            original = img;
            scaled = original;
        }

        @Override
        public Dimension getPreferredSize() {
            return original == null ? new Dimension(200, 200) : new Dimension(original.getWidth(), original.getHeight());
        }

        @Override
        public void invalidate() {
            super.invalidate();
            generateScaledInstance();
        }

        protected void generateScaledInstance() {
            if (original != null) {

                scaled = getScaledInstanceToFill(original, getSize());

            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            if (scaled != null) {
                int x = (getWidth() - scaled.getWidth()) / 2;
                int y = (getHeight() - scaled.getHeight()) / 2;
                g2d.drawImage(scaled, x, y, this);
            }
            g2d.dispose();
        }

        public BufferedImage getScaledInstanceToFill(BufferedImage img, Dimension size) {
            float scaleFactor = getScaleFactorToFill(img, size);
            return getScaledInstance(img, scaleFactor);
        }

        public float getScaleFactorToFill(BufferedImage img, Dimension size) {
            float scale = 1f;
            if (img != null) {
                int imageWidth = img.getWidth();
                int imageHeight = img.getHeight();
                scale = getScaleFactorToFill(new Dimension(imageWidth, imageHeight), size);
            }
            return scale;
        }

        public float getScaleFactorToFill(Dimension original, Dimension toFit) {
            float scale = 1f;
            if (original != null && toFit != null) {
                float dScaleWidth = getScaleFactor(original.width, toFit.width);
                float dScaleHeight = getScaleFactor(original.height, toFit.height);
                scale = Math.max(dScaleHeight, dScaleWidth);
            }
            return scale;
        }

        public float getScaleFactor(int iMasterSize, int iTargetSize) {
            float scale = 1;
            if (iMasterSize > iTargetSize) {
                scale = (float) iTargetSize / (float) iMasterSize;
            } else {
                scale = (float) iTargetSize / (float) iMasterSize;
            }
            return scale;
        }

        public BufferedImage getScaledInstance(BufferedImage img, double dScaleFactor) {
            BufferedImage imgBuffer = null;
            imgBuffer = getScaledInstance(img, dScaleFactor, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
            return imgBuffer;
        }

        protected BufferedImage getScaledInstance(BufferedImage img, double dScaleFactor, Object hint, boolean higherQuality) {

            BufferedImage scaled = img;
            if (dScaleFactor != 1.0) {
                if (dScaleFactor > 1.0) {
                    scaled = getScaledUpInstance(img, dScaleFactor, hint, higherQuality);
                } else if (dScaleFactor > 0.0) {
                    scaled = getScaledDownInstance(img, dScaleFactor, hint, higherQuality);
                }
            }

            return scaled;

        }

        protected BufferedImage getScaledDownInstance(BufferedImage img, double dScaleFactor, Object hint, boolean higherQuality) {

            int targetWidth = (int) Math.round(img.getWidth() * dScaleFactor);
            int targetHeight = (int) Math.round(img.getHeight() * dScaleFactor);

            int type = (img.getTransparency() == Transparency.OPAQUE)
                            ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

            BufferedImage ret = (BufferedImage) img;

            if (targetHeight > 0 || targetWidth > 0) {
                int w, h;
                if (higherQuality) {
                    w = img.getWidth();
                    h = img.getHeight();
                } else {
                    w = targetWidth;
                    h = targetHeight;
                }

                do {
                    if (higherQuality && w > targetWidth) {
                        w /= 2;
                        if (w < targetWidth) {
                            w = targetWidth;
                        }
                    }

                    if (higherQuality && h > targetHeight) {
                        h /= 2;
                        if (h < targetHeight) {
                            h = targetHeight;
                        }
                    }

                    BufferedImage tmp = new BufferedImage(Math.max(w, 1), Math.max(h, 1), type);
                    Graphics2D g2 = tmp.createGraphics();
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
                    g2.drawImage(ret, 0, 0, w, h, null);
                    g2.dispose();

                    ret = tmp;
                } while (w != targetWidth || h != targetHeight);
            } else {
                ret = new BufferedImage(1, 1, type);
            }
            return ret;
        }

        protected BufferedImage getScaledUpInstance(BufferedImage img,
                        double dScaleFactor,
                        Object hint,
                        boolean higherQuality) {

            int targetWidth = (int) Math.round(img.getWidth() * dScaleFactor);
            int targetHeight = (int) Math.round(img.getHeight() * dScaleFactor);

            int type = BufferedImage.TYPE_INT_ARGB;

            BufferedImage ret = (BufferedImage) img;
            int w, h;
            if (higherQuality) {

                w = img.getWidth();
                h = img.getHeight();

            } else {

                w = targetWidth;
                h = targetHeight;

            }

            do {

                if (higherQuality && w < targetWidth) {

                    w *= 2;
                    if (w > targetWidth) {

                        w = targetWidth;

                    }

                }

                if (higherQuality && h < targetHeight) {

                    h *= 2;
                    if (h > targetHeight) {

                        h = targetHeight;

                    }

                }

                BufferedImage tmp = new BufferedImage(w, h, type);
                Graphics2D g2 = tmp.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
                g2.drawImage(ret, 0, 0, w, h, null);
                g2.dispose();

                ret = tmp;
                tmp = null;

            } while (w != targetWidth || h != targetHeight);

            return ret;

        }

    }

}

This example will grow and shrink as the image as the amount of available space for the panel changes

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2

You can use the Stretch Icon on your JLabel.

Or you could use the Background Panel to draw the image.

In both cases the Image will shrink or grow as the frame is resized.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

First get the Image, then use this method:

yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

You can get the width and height from the JFrame. Then you can convert the Image to ImageIcon and add it.

Bitcoin M
  • 1,206
  • 8
  • 24