繁体   English   中英

Java Swing-如何在Jpanel北部添加图像

[英]Java Swing - how to add image in north of Jpanel

我想在JPanel NORTH部分添加图像,但是它不起作用。 我该怎么办?

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);
    } 
}

这是您的代码的有效修改。 您应该能够按原样运行它。 本质上,您不能简单地将ImageIcon添加到JPanel 您需要先将其包装在JLabel

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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