import javax.swing.*;import java.awt.*;public class Test extends JFrame{ ImageIcon icon;
JPanel jp1;
public Test()
{
this.add(buildWestJpanel());
this.setSize(350,350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public JPanel buildWestJpanel()
{
jp1 = new JPanel();
if(icon ==null)
{
icon = new ImageIcon("login.gif");
}
jp1.repaint();
return jp1;
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawImage(icon.getImage(),0,0,350,89,jp1);
}
public static void main(String args[])
{
new Test();
}
}为什么这段代码不能把login.gif插入进去,也就是我运行不显示图片
JPanel jp1;
public Test()
{
this.add(buildWestJpanel());
this.setSize(350,350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public JPanel buildWestJpanel()
{
jp1 = new JPanel();
if(icon ==null)
{
icon = new ImageIcon("login.gif");
}
jp1.repaint();
return jp1;
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawImage(icon.getImage(),0,0,350,89,jp1);
}
public static void main(String args[])
{
new Test();
}
}为什么这段代码不能把login.gif插入进去,也就是我运行不显示图片
重写的这个方法设计的就不好,应该重写一个JPanel比较合适,给你贴出来代码了,你自己看看import javax.swing.*;
import java.awt.*;public class Test extends JFrame{
JPanel jp1;
Container container=null; public Test()
{
container=this.getContentPane();
container.add(buildWestJpanel());
this.setSize(350,350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public JPanel buildWestJpanel()
{
jp1 = new MyPanel();
jp1.repaint();
return jp1;
}
public static void main(String args[])
{
new Test();
}
}class MyPanel extends JPanel{
ImageIcon icon= new ImageIcon("login.gif");
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of overridden methods use File | Settings | File Templates.
g.drawImage(icon.getImage(),0,0,350,89,null);
}
}