[英]Java Swing - how to add image in north of Jpanel
I want to add image in NORTH
part of my JPanel
, but it doesnt work. 我想在JPanel
NORTH
部分添加图像,但是它不起作用。 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);
}
}
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
. 本质上,您不能简单地将ImageIcon
添加到JPanel
。 You need to wrap it in a JLabel
first. 您需要先将其包装在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.