我希望在JPanel中调整ImageIcon的大小,并且我知道到处都有建议,无论我如何编辑,该建议都不适用于以下内容。以下是我发现最接近我的目标的众多尝试之一。

来自:resizing a ImageIcon in a JButton

我该如何纠正我的代码?

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

最佳答案

尝试这个。但是您固定了标签和imageicon的大小。因此不必担心jpanel的大小。

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

10-07 12:18