2011-04-20 4 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

무엇을하고 있습니까? 오류? –

+0

아마도 당신이 기대하는 바를 설명 할 수 있습니까? – WhiteFang34

답변

2

당신은 JFrame 또는 JDialog가에 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

2

당신이하려고하는 것이 확실하지 않지만 코드가 이전 AWT 예제와 유사하므로 Swing에 사용하면 안됩니다.

  1. 업데이 트를 오버라이드 (override) 할 필요가 없다()
  2. 의 paintComponent()()

super.paintComponent를 호출 라벨 이미지를 사용 예제 코드에 대한 How to Use Icons에 스윙 튜토리얼을 읽어해야합니다.

관련 문제