簡體   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