1

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);
4

2 回答 2

3

您正在混合布局管理器的绝对定位和使用。当您调用or时,您使用的是绝对布局,即您手动管理组件的大小和位置。setSize()setBounds()

当您调用 时pack(),您将大小和定位委托给框架内组件的 LayoutManager。LayoutManager 的位置和大小基于组件的首选/最小/最大大小和约束。在此处查看有关 LayoutManager 的所有信息。

我建议依赖 LayoutManagers,因为它在不同平台上运行得更好,而且你的代码会更干净。

于 2012-05-24T06:34:20.407 回答
3
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);
            }
        });
    }
}
于 2012-05-24T15:40:50.913 回答