2010-03-05 109 views
0

我使用Graphics類和drawImage()方法將圖片大小調整爲100x100大小。但我無法將調整大小的圖像加載到JLabel中。是否有可能將調整大小的圖片加載到JLabel中?將圖片調整爲100x100大小並加載到JLabel中調整大小的圖片中?

Image image = jfc.getSelectedFile(); 
ImageIcon Logo = new ImageIcon(image.getPath()); 
BufferedImage resizedImage = new BufferedImage(width, height, 
BufferedImage.TYPE_INT_ARGB); 
Graphics2D g = resizedImage.createGraphics(); 
g.drawImage(image, 0, 0, 100, 100, null); // Here i resized. But after that how can i load into Jlabel? 

JLabel labelLogo; 
labelLogo.setIcon(Logo); 
...? 
+0

請使用代碼標籤,使您的條目顯示理智格式化。 – crazyscot 2010-03-05 07:49:33

+0

crazyscot:非常感謝 – Venkat 2010-03-05 12:41:09

回答

2

這裏有一個例子:你possibliy需要actionPerformed()修改組件後更新的佈局。

public static void main(String[] args) { 
    JFrame frame = new JFrame(); 
    final Container panel = frame.getContentPane(); 
    panel.setLayout(new FlowLayout()); 

    // create an image an draw in it. 
    final BufferedImage image = new BufferedImage(
     200, 200, BufferedImage.TYPE_INT_ARGB); 
    Graphics g = image.getGraphics(); 
    g.setColor(Color.RED); 
    g.drawLine(0, 0, image.getWidth(), image.getHeight()); 

    Icon iImage = new ImageIcon(image); 
    // create a label with the icon. 
    final JLabel label = new JLabel(iImage); 
    panel.add(label); 
    // create a new button. 
    JButton button = new JButton("resize"); 
    // add an action to the button. 
    button.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) { 
      // set the label with a new icon. 
      BufferedImage bi = new BufferedImage(
       100, 100, BufferedImage.TYPE_INT_ARGB); 
      bi.getGraphics().drawImage(image, 0, 0, null); 
      label.setIcon(new ImageIcon(bi)); 
     } 
    }); 
    // add the button to the frame. 
    panel.add(button); 
    // open the frame. 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.pack(); 
    frame.setVisible(true); 
} 
+0

哦,這篇文章說不要使用getScaledInstance ... http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html – ultrajohn 2010-03-05 08:21:18

+0

thx爲文章。 – elou 2010-03-05 09:44:59

+0

我冒昧地重新格式化了您評論良好的代碼,並添加了'pack()'&'setDefaultCloseOperation()'。 – trashgod 2010-03-05 16:48:03

0

這篇文章中說了一些關於避免使用getScaledInstance方法,同時還提供了一些可供選擇的方法...

link to article

+0

例行修正。 – elou 2010-03-05 09:47:17