2013-10-23 45 views
0

我希望調整JPanel中的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); 
+0

'lblFoodPicUrl = new ImageIcon(newing);'這段代碼應該做什麼? – Sage

+0

謝謝你,我從這個方式得到的參考。所以我正試圖將貢獻者的建議付諸實施。 – brainsfrying

回答

0

試試這個。但是您修復了標籤和圖片大小。所以它不關心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)); 
相關問題