简体   繁体   中英

Can't add JLabel to JPanel

I have this code:

  ImageIcon ii = new ImageIcon("https://c1.staticflickr.com/9/8384/8682624224_4e44bf947d_h.jpg"); 
  subStream.add(new JLabel(ii));

It's meant to add JLabel with photo to JPanel called subStream . But it doesn't work, no errors or anything. Why so?

在此处输入图片说明

Image is supposed to appear in 3rd JPanel, just above Buttons.

Things to be aware of...

  • ImageIcon can fail silently...annoying I know...this is because...
  • ImageIcon uses a background thread to load the images, this is because it was designed to allow for slow sources (dial up networks) which might need time to fully realise the image.

You should use ImageIO.read to test the URL to discount potential issues with downloading the image. This will throw an IOException if the image can't be loaded for some reason and will block until the image is fully loaded, so beware of that

See Reading/Loading an Image for more details

For example...

下载图片

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                try {
                    BufferedImage img = ImageIO.read(new URL("https://c1.staticflickr.com/9/8384/8682624224_4e44bf947d_h.jpg"));
                    JLabel label = new JLabel(new ImageIcon(img));

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(label);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

}

So, this discounts the image and web server as the potential problem (at least from within my network), there must be something else wrong with your code. Consider providing a runnable example which demonstrates your problem. This will result in less confusion and better responses

You are invoking ImageIcon(String filename) constructor. Try with the URL one:

ImageIcon icon = new ImageIcon(new URL("your URL"));

// Imports
// ...

public class MyFrame extends JFrame
{
    public MyFrame()
    {
        super("Test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        try
        {
            URL url = new URL("http://upload.wikimedia.org/wikipedia/it/0/0b/Vegeta_-_Sigla_Iniziale_Dragon_Ball_Kai.jpg");

            getContentPane().add(new JLabel(new ImageIcon(url)));
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

        pack();
        setLocationRelativeTo(null);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() ->
        {
            new MyFrame().setVisible(true);
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM