开发者

auto resize content of label

I have a label in my program that displays an image. The problem is, if an image is selected that is larger than the label, only part of the i开发者_开发问答mage is displayed.

How do I display the entire image?

image = new ImageIcon(movpath);     
l5=new JLabel(image);
l5.setBounds(360,300,200,200);
p1.add(l5);

Help needed in reference with the above code


There is no need to write custom code for this. The JLabel will automatically resize itself when you change the Icon.

The problem is that you are using a null layout and the size is fixed to (200, 200) so the label can't grow or shrink.

If you want to have a fixed area to display the label then add the label to a scrollpane and set the preferred size of the scroll pane. Then scrollbars will appear if necessary.

Get rid of the null layout and design a proper GUI by using layout managers. You will save yourself a lot of grief.

Since you are asking a lot of beginner questions I suggest you start by reading the Swing tutorial for the basics. Layout managers are well covered.


Got the way for the above scenario. For resizing use the following code:

image = new ImageIcon(movpath);

    l5 = new JLabel ()
    { 

        public void paintComponent (Graphics g) 
        { 
            super.paintComponent (g); 
            g.drawImage (image.getImage(), 0, 0, getWidth (), getHeight (), null); 
        } 
    }; 
    l5.setBounds(360,300,200,200);
    p1.add(l5);
    l5.addMouseListener(this);


To resize the image to the size of your JLabel, you need the following:

l5 = new JLabel ()
{ 
    public void paintComponent (Graphics g) 
    { 
        super.paintComponent (g); 
        g.drawImage (image.getScaledInstance(getWidth(), getHeight(), Image.SCALE_DEFAULT), 0, 0, getWidth (), getHeight (), this); 
    } 
}; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜