0

I have an image that is too tall for my JFrame even when it is maximized. I want to dynamically resize it so that the image will never be clipped by the top or bottom of the JFrame. I have inserted the image within a JLabel as an ImageIcon. I have tried setting the maximum size to no avail. How do I ensure that the height of the image will never be larger than the JFrame? I would ideally like to keep the ratio of height to width constant. The image is in a portrait orientation. Any ideas?

public class myClass extends JFrame {   
private void initGUI(){
    pane = getContentPane();
    pane.setLayout(new BorderLayout());

    next = new JButton("Next");


    previous = new JButton("Previous");

    page = new JLabel(loadImg());
    page.setMaximumSize(this.getSize());
    pane.add(next, BorderLayout.EAST);
    pane.add(previous, BorderLayout.WEST);
    pane.add(page, BorderLayout.CENTER);
}
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Skylion
  • 2,696
  • 26
  • 50
  • I'd like to note that you are setting the size before there is anything in the actual content pane. – Josh M Nov 17 '13 at 22:51
  • I have edited the code to make it more clear – Skylion Nov 17 '13 at 22:52
  • You could take a look at [this](http://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image/11959928#11959928) and [this](http://stackoverflow.com/questions/14548808/scale-the-imageicon-automatically-to-label-size/14553003#14553003) – MadProgrammer Nov 17 '13 at 23:04

2 Answers2

1

I would ideally like to keep the ratio of height to width constant.

Check out Darryl's Stretch Icon. It will shrink/grow depending on the space available, while maintaining the width/height ratio.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

You can try overriding the paintComponent(Graphics g) method and drawing the resized image yourself.

    page = new JLabel(loadIMG()){
        @Override
        paintComponent(Graphics g)
        {
            //So we don't kill default behaviour
            super.paintComponent(g);

            int scaledWidth, scaledHeight;

            //pseudo-code
            scale and store into scaledWidth and scaledHeight;

           render with g.drawImage(icon, x, y, scaledWidth, scaledHeight, null);
        }
    };
Brett
  • 159
  • 1
  • 8