简体   繁体   中英

java: how to resize a frame containg image

I have created one frame and displaying an image into frame. but I am unable set the size of a frame. As i have tried following code, but its giving me the part of image i have set, Not the whole image. Please help me to re-size the image.

JFrame frame = new JFrame("My Window");
frame.setSize(200,200);
int frameWidth = 200;
int frameHeight = 200;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds((int) screenSize.getWidth() - frameWidth, 0, frameWidth, frameHeight);
frame.pack();
frame.setVisible(true);

You are mixing absolute positioning and usage of layout managers . When you call setSize() or setBounds() , you are using absolute layout, ie, you manage manually the size and location of your components.

When you call pack() , you delegate the sizing and positioning to the LayoutManagers of the component inside your frame. LayoutManager's position and size the components based on their preferred/minimum/maximum size and constraints. See all about LayoutManager's here .

I would recommend to rely on LayoutManagers because it works better across different platforms and your code will be cleaner.

package test.t100.t004;

import java.awt.Image;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class ImageSizedGUI {

    ImageSizedGUI(Image image) {
        JLabel label = new JLabel(new ImageIcon(image));

        JFrame f = new JFrame("Image");
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // either this, or..
        f.setContentPane(new JScrollPane(label));

        f.pack();
        // ..this, but could produce undesirable results for images 
        // that are larger than screen size!
        // f.setMinimumSize(f.getSize());
        f.setLocationByPlatform(true);
        f.setVisible(true);
    }

    public static void main(String[] args) throws Exception {
        String address = (args.length>0 ? args[0] :
                "http://pscode.org/media/stromlo2.jpg");
        URL url = new URL(address);
        final Image image = ImageIO.read(url);
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new ImageSizedGUI(image);
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM