Adjust the image as per screen resolution of window

戏子无情 提交于 2019-12-11 11:17:52

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/7980272/adjust-the-image-as-per-screen-resolution-of-window

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