简体   繁体   中英

Java Swing - why cant I add image to Jpanel?

I dont know why I cant add image to my JPanel i use code:

class PanelGlowny extends JPanel {

    private JLabel adam;
    private JButton henryk;

    PanelGlowny(){

        this.setLayout(new BorderLayout());
        ImageIcon imageurl = new ImageIcon("logo.jpg");
        //Image img = imageurl.getImage();
        adam = new JLabel(imageurl);
        add(adam, BorderLayout.NORTH);
        henryk = new JButton();
        add(henryk, BorderLayout.CENTER);

    }
}

Image is in the same folder as class, but if I use url to image it also do not add anything. This code adding button, but do not add image :(

The problem is probably with my JDE, or Sandbox or sth like this, because code should be fine.

Try this:

imageurl = new ImageIcon(getClass().getResource("logo.jpg"));

Check How to Use Icons tutorial.

EDIT : loading remote image

Try that to load your image from web:

public static void main(String args[]) {
    try {
        JOptionPane.showMessageDialog(null, "", "", 
            JOptionPane.INFORMATION_MESSAGE, 
            new ImageIcon(new URL("http://marinerczarter.pl/wp-content/themes/twentyten/images/headers/path.jpg")));
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    } 
}

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