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插入进去,也就是我运行不显示图片

解决方案 »

  1.   

    你重写的protected void paintComponent(Graphics g) 从头到尾都没有执行
    重写的这个方法设计的就不好,应该重写一个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);
        }
    }
      

  2.   

    直接使用JLabel显示图片了,哪里来的那些麻烦事
      

  3.   

    谢谢 了。。怪不得 总觉的那里错了。。我开始以为 是repaint会自动调用paintComponent()。。