我想在我的 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 );
}
}
关于Java Swing - 如何在Jpanel的北部添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9997578/