简体   繁体   中英

Java Swing - how to add image in north of Jpanel

I want to add image in NORTH part of my JPanel , but it doesnt work. What should i do?

class PanelGlowny extends JPanel 
{    
    PanelGlowny()
    {        
        this.setLayout(new BorderLayout());
        ImageIcon imageurl = new ImageIcon("logo.jpg");
        Image img = imageurl.getImage();
        this.add(img, BorderLayout.NORTH);

    }
}

public class Formatka extends JFrame 
{    
    private PanelGlowny panel = new PanelGlowny();

    public Formatka()
    {    
        ...
        add(panel);
    } 
}

Here's a working modification of your code. You should be able to run it as is. Essentially, you can't simply add the ImageIcon to the JPanel . You need to wrap it in a JLabel first.

import java.awt.BorderLayout;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test2
{
    public static class PanelGlowny extends JPanel
    {

        public PanelGlowny( )
        {

            this.setLayout( new BorderLayout( ) );

            // incorporated @nIcE cOw's comment about loading classpath resources
            URL url = getClass().getResource("logo.jpg")
            ImageIcon imageicon = new ImageIcon( url );
            JLabel label = new JLabel( imageicon );

            this.add( label, BorderLayout.NORTH );

        }
    }

    public static void main( String[] args )
    {
        JFrame frame = new JFrame( );

        frame.add( new PanelGlowny( ) );

        frame.setSize( 400, 400 );

        frame.setVisible( true );
    }

}

ImageIcon创建一个新的JLabel并将其添加到JPanel

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