在JPanel中调整ImageIcon,从文件夹中检索文件

时间:2013-10-23 13:27:14

标签: java swing jpanel jlabel imageicon

我希望在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);

2 个答案:

答案 0 :(得分:2)

尝试使用Darryl的Stretch Icon。如果标签的大小发生变化,它应该动态调整图标大小。

答案 1 :(得分:0)

试试这个。但你修复了你的标签和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));