yeshwant Lautre
yeshwant Lautre

Reputation: 21

Adjust the image as per screen resolution of window

I have add a JLabel in a JFrame and one image of size 1024x768 is added in JLabel.

When I set the resolution of window screen in 1024x768 the and run the application the image is shown in full window. But when I set the resolution of window screen in 1280x768 - the image is shown in only one third portion of window.

How can I adjust or add the image of size 1024x768 so that in any screen resolution the image will show covering the full window? In other words the image is adjusted as per the screen resolution of window.

Upvotes: 1

Views: 1070

Answers (2)

Ravi Kiran
Ravi Kiran

Reputation: 11

I have faced this problem several times while i was adding image to the JFrame. Either the image size would be small or the JFrame size was small.

Here is a great site wherein you can resize your images according to the JFrame without distorting the image.

You can visit this website Go to the site

I have explained and showed how to make use of photo editor that the website provides to resize the image.

Go to my video tutorial Go to the Video Session

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168815

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
import javax.imageio.ImageIO;

class ImagePanel extends JPanel {

    Image image;

    ImagePanel(Image image) {
        this.image = image;
    }

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

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://pscode.org/media/stromlo2.jpg");
        final Image image = ImageIO.read(url);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame("Image");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setLocationByPlatform(true);

                ImagePanel imagePanel = new ImagePanel(image);
                imagePanel.setLayout(new GridLayout(5,10,10,10));
                imagePanel.setBorder(new EmptyBorder(20,20,20,20));
                for (int ii=1; ii<51; ii++) {
                    imagePanel.add(new JButton("" + ii));
                }

                f.setContentPane(imagePanel);
                f.pack();
                f.setVisible(true);
            }
        });
    }
}

Raw image used

Raw image

Upvotes: 3

Related Questions