0

I wish to resize an ImageIcon within a JPanel, and I know there are suggestions everywhere, where it does not work for the following no matter how I edit it. The following is one of the many attempts, which i find closest to my aim.

With courtesy from: resizing a ImageIcon in a JButton

How can i rectify my code?

        JLabel lblFoodPicUrl = new JLabel();
        lblFoodPicUrl.setPreferredSize(new Dimension (50,50));
        lblFoodPicUrl.setIcon (new ImageIcon (PlaceOrder.class.getResource("/Pictures/" + food_Pic_Url + ".jpg")));
        lblFoodPicUrl.setHorizontalAlignment (SwingConstants.CENTER);


        Image img = (Image) lblFoodPicUrl.getIcon();
        Image newing = img.getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH);
        lblFoodPicUrl = new ImageIcon (newing);
Community
  • 1
  • 1
brainsfrying
  • 241
  • 1
  • 6
  • 21

2 Answers2

2

Try using Darryl's Stretch Icon. It should dynamically resize the icon if the size of the label ever changes.

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

try this. but you fixed your label and imageicon size. so it is not bother about jpanel size.

    JLabel lblFoodPicUrl = new JLabel();
    lblFoodPicUrl.setPreferredSize(new Dimension(50, 50));
    lblFoodPicUrl.setIcon(new ImageIcon(getClass().getResource("your path")));
    lblFoodPicUrl.setHorizontalAlignment(SwingConstants.CENTER);
    BufferedImage img = new BufferedImage(lblFoodPicUrl.getIcon().getIconWidth(), lblFoodPicUrl.getIcon().getIconHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = img.createGraphics();
    lblFoodPicUrl.getIcon().paintIcon(null, g, 0, 0);
    g.dispose();
    Image newing = img.getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH);
    lblFoodPicUrl.setIcon(new ImageIcon(newing));
subash
  • 3,116
  • 3
  • 18
  • 22