0
try {
    addImage(bodyPanel1, "https://sneakernews.com/wp-content/uploads/2020/10/jordan-1-black-mocha-555088-105-2.jpg");
} catch (MalformedURLException e) {
    e.printStackTrace();
}


private void addImage(JPanel cp, String url) throws MalformedURLException{
    cp.add(new JLabel(new ImageIcon(new URL(url))));
}

So I am trying to insert the image using a URL and then have it resize to the size of the bodypanel but whenever i try to run it the image doesnt scale itself. I have the entire bodypanel in a grid layout (3 row, 2 columns) and want to add an image to fit the entire size of one of the grid boxes. image

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

0

Try this code I found (Link to code | Link to the guy who originally found this code):

ImageIcon imageIcon = new ImageIcon(new URL(url)); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it 
Image newimg = image.getScaledInstance(120, 120,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
imageIcon = new ImageIcon(newimg);
cp.add(new JLabel(imageIcon));
IntoVoid
  • 914
  • 4
  • 7
0
    ImageIcon originalIcon = new ImageIcon("slovakia.png");
    JLabel originalLabel = new JLabel(originalIcon);

    int width = originalIcon.getIconWidth() / 2;
    int height = originalIcon.getIconHeight() / 2;

    Image scaled = scaleImage(originalIcon.getImage(), width, height);

    ImageIcon scaledIcon = new ImageIcon(scaled);

    JLabel newLabel = new JLabel(scaledIcon);