0

I have a JFrame that shoud show an image (retrieved from web) and two lateral buttons for show next and previous image. Original image size is too big, and i would scale it before show. this is my code:

public class ShowPicture extends JFrame implements ActionListener {

private String link;
private JButton next;
private JButton prev;
private Image image;

public ShowPicture(String link) {
    this.setSize(300, 200);
    setLocationRelativeTo(null); //center
    setVisible(true);

    this.link = link;
    this.setLayout(new FlowLayout());

    prev = new JButton("prev");
    next = new JButton("next");

    URL url;
    try {
        url = new URL(link + "/front.jpg");
        image = ImageIO.read(url);
    } catch (MalformedURLException ex) {
        Logger.getLogger(ShowPicture.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ShowPicture.class.getName()).log(Level.SEVERE, null, ex);
    }

    JLabel image_label = new JLabel(new ImageIcon(image));
    image_label.setSize(100, 100);

    this.add(prev);
    this.add(image_label);
    this.add(next);

    pack();
}

but image is not scaled

how can i do?

giozh
  • 9,868
  • 30
  • 102
  • 183
  • A similar question (which holds the answer to your question) has already been asked: http://stackoverflow.com/questions/6714045/how-to-resize-jlabel-imageicon – headcr4sh Jan 15 '15 at 15:00

1 Answers1

2

I would scaled the image itself not the JLabel. Use :

image = ImageIO.read(url);
image = image.getScaledInstance(100,100,Image.SCALE_DEFAULT);
JLabel image_label = new JLabel(new ImageIcon(image));
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • 2
    About **getScaledInstance**, please, take a look [here](https://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html). – fscherrer Jan 15 '15 at 15:22
  • The original getScaledInstance blog is gone, but can still be seen at https://web.archive.org/web/20150510025421/https://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html. – VGR Dec 15 '18 at 17:45