tags:

views:

59

answers:

3

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 image 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

A: 

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);
+1  A: 

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.

camickr
A: 

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); 
    } 
}; 
Devon_C_Miller