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

标签 java image swing

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

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

}

关于Java Swing - 如何在Jpanel的北部添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9997578/

相关文章:

java - 如何将主类中的TCP连接变量传递给另一个JFrame类?

java - 使用 BorderLayout 从 JPanel 中删除 CENTER 元素

java - 我可以在 Spring Controller 类中使用路径变量吗?

java - itext7,html转pdf无法换行长英文单词或长数字

Java 从随机数循环中排除 0 - 我的解决方案可能会出现哪些问题?

html - 如何: auto resize featured image,博主?

java - 如果图片尺寸过大,将无法加载

java - 从 Cloud Firestore 中的一个集合中获取所有文档?

c++ - OpenCV 透视图

java - 如何有效实现数据库功能?