2011-04-20 89 views
1

我不明白爲什麼這段代碼不會工作。有任何想法嗎?在JPanel中加載圖像?

import java.awt.Graphics; 
import java.awt.Image; 
import java.awt.Insets; 
import java.awt.Toolkit; 
import java.awt.image.ImageObserver; 
import java.net.URL; 

import javax.swing.JPanel; 

public class ImageTool extends JPanel { 

    private static final long serialVersionUID = 1L; 
    private static Image image; 

    public ImageTool(URL url) {  
    image = Toolkit.getDefaultToolkit().getImage(url); 
    rightSize(); 
    } 

    private void rightSize() { 
    int width = image.getWidth(this); 
    int height = image.getHeight(this); 
    if (width == -1 || height == -1) 
     return; 
    addNotify(); 
    System.out.println("Image width: "+width); 
    System.out.println("Image height"+height); 

    } 

    public boolean imageUpdate(Image img, int infoflags, int x, int y, 
     int width, int height) { 
    if ((infoflags & ImageObserver.ERROR) != 0) { 
     System.out.println("Error loading image!"); 
     System.exit(-1); 
    } 
    if ((infoflags & ImageObserver.WIDTH) != 0 
     && (infoflags & ImageObserver.HEIGHT) != 0) { 
     rightSize(); 
     System.out.println("1"); 
    } 
    if ((infoflags & ImageObserver.SOMEBITS) != 0) 
     repaint(); 
    if ((infoflags & ImageObserver.ALLBITS) != 0) { 
     System.out.println("2"); 
     rightSize(); 
     repaint(); 
     return false; 
    } 
    return true; 
    } 

    public void update(Graphics g) { 
    paint(g); 
    } 

    public void paintComponent(Graphics g) { 
    Insets insets = getInsets(); 
    g.drawImage(image, insets.left, insets.top, this); 
    } 
    public static void main(String[] args) throws Exception { 
    String url = "http://www.java2s.com/style/logo.png"; 
    new ImageTool(new URL(url)); 

    } 
} 
+0

它在做什麼?錯誤? – 2011-04-20 03:33:19

+0

也許你可以解釋你期望它做什麼? – WhiteFang34 2011-04-20 03:39:24

回答

2

在你的代碼你缺少一個JFrameJDialog包含在你的JPanel。下面是我相信不會你問的一個例子。它將相同的圖像加載到可見窗口中並將尺寸輸出到控制檯。

public class ImageTool extends JPanel { 
    public ImageTool(URL url) { 
     ImageIcon icon = new ImageIcon(url); 
     JLabel label = new JLabel(icon, JLabel.CENTER); 
     add(label); 

     System.out.println("Image width: " + icon.getIconWidth()); 
     System.out.println("Image height: " + icon.getIconHeight()); 
    } 

    public static void main(String[] args) throws MalformedURLException { 
     URL url = new URL("http://www.java2s.com/style/logo.png"); 
     JPanel panel = new ImageTool(url); 
     JFrame frame = new JFrame(); 
     frame.add(panel); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 
+0

是的,那完美的作品。非常感謝。只是想學習這些東西。 – djangofan 2011-04-20 16:43:44

2

我不確定你想要做什麼,但你的代碼看起來像一箇舊的AWT示例,不應該用於Swing。

  1. 沒有必要重寫更新()
  2. 的paintComponent()應該調用super.paintComponent方法()

閱讀How to Use Icons例如代碼,在標籤上使用圖像的Swing教程。