Java Swing - 如何在Jpanel的北部添加图像 [英] Java Swing - how to add image in north of Jpanel
本文介绍了Java Swing - 如何在Jpanel的北部添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 NORTH
部分我的 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);
}
}
推荐答案
这里是代码的工作修改。你应该能够按原样运行它。基本上,您不能简单地将 ImageIcon
添加到 JPanel
。您需要首先将其包装在 JLabel
中。
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 );
}
}
这篇关于Java Swing - 如何在Jpanel的北部添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文