更新时间:2023-12-05 10:57:52
这里是代码的工作修改。你应该能够按原样运行它。基本上,您不能简单地将 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 );
}
}