图像显示文件目录,但不显示URL

时间:2022-08-14 20:22:40

Program works when I link to an image on my program (current code). when I replace that with a URL ("http://www.digitalphotoartistry.com/rose1.jpg"), the program will run without the image being displayed. I've tried a lot of variations with no luck. Can anyone see why it's not working?

当我链接到我的程序上的图像(当前代码)时,程序工作。当我用URL(“http://www.digitalphotoartistry.com/rose1.jpg”)替换它时,程序将在没有显示图像的情况下运行。我尝试了很多变化而没有运气。谁能明白为什么它不起作用?

public class ImageViewer extends JFrame {

public ImageViewer() {
    //create panel of actions
    JPanel actionPanel = new JPanel();
    actionPanel.setLayout(new GridLayout(1, 4));

    actionPanel.add(new JButton("Prev"));
    actionPanel.add(new JButton("Add"));
    actionPanel.add(new JButton("Del"));
    actionPanel.add(new JButton("Next"));


    //Create panel to hold pictures
    JLabel label= new JLabel(new ImageIcon("C:/Users/Madison/Desktop/capture.png"), JLabel.CENTER);
    JPanel imagePanel = new JPanel(new BorderLayout());
    imagePanel.add(label, BorderLayout.CENTER );

    //Add contents to frame
    add(imagePanel, BorderLayout.NORTH);
    add(actionPanel, BorderLayout.SOUTH);
}

public static void main (String args []){
    ImageViewer frame = new ImageViewer();
    frame.setTitle("Title");
    frame.setSize(1000, 500);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

}

1 个解决方案

#1


1  

Are you editing your code accordingly? You can't just replace the path with the url.

你是否相应地编辑你的代码?您不能只用网址替换路径。

Try this:

URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg"); //set url
ImageIcon image = new ImageIcon(ImageIO.read(url)); //read image and create ImageIcon
JLabel label = new JLabel(image, JLabel.CENTER);    

Remember to check for IO and MalformedURL Exceptions.

请记住检查IO和MalformedURL例外。

#1


1  

Are you editing your code accordingly? You can't just replace the path with the url.

你是否相应地编辑你的代码?您不能只用网址替换路径。

Try this:

URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg"); //set url
ImageIcon image = new ImageIcon(ImageIO.read(url)); //read image and create ImageIcon
JLabel label = new JLabel(image, JLabel.CENTER);    

Remember to check for IO and MalformedURL Exceptions.

请记住检查IO和MalformedURL例外。