"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Java JPanel의 URL에서 이미지를 표시하려면 어떻게 해야 합니까?

Java JPanel의 URL에서 이미지를 표시하려면 어떻게 해야 합니까?

2024년 11월 19일에 게시됨
검색:614

How can I display an image from a URL in a Java JPanel?

이미지를 표시하려면 ImageIcon 클래스를 사용하여 URL에서 이미지를 로드할 수 있습니다. 그런 다음 ImageIcon을 JLabel에 추가한 후 JPanel에 추가할 수 있습니다.

다음은 URL에서 이미지를 로드하고 JPanel에 표시하는 방법에 대한 예입니다.

import java.awt.Image;
import java.awt.image.ImageIcon;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class DisplayImage {

    public static void main(String[] args) {
        // Create a panel to hold the image
        JPanel panel = new JPanel();

        // Load the image from a URL
        Image image = Toolkit.getDefaultToolkit().getImage(new URL("http://www.example.com/image.jpg"));

        // Create an ImageIcon from the image
        ImageIcon icon = new ImageIcon(image);

        // Create a label to hold the image icon
        JLabel label = new JLabel(icon);

        // Add the label to the panel
        panel.add(label);

        // Add the panel to the frame
        JFrame frame = new JFrame();
        frame.getContentPane().add(panel);

        // Set the size of the frame
        frame.setSize(400, 400);

        // Display the frame
        frame.setVisible(true);
    }
}

이 코드는 지정된 URL에서 이미지를 로드하고 JPanel에 표시합니다. 이미지의 크기는 JPanel의 크기에 따라 결정됩니다.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3