谁会在jpanel上添加图片呀   为什么在jframe可以添加 可是一到jpanel就不行了 为什么呀 

解决方案 »

  1.   

    有这种需求的话,我就用 swingx了。
    提供了 setBackgroundPainter 方法,可以使用图片作为背景。
      

  2.   

    class MyPanel extends JPanel {

    private Image image = null;

    public void setImage(Image image) {
    this.image = image;
    repaint();
    } @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (image != null) {
    g.drawImage(image, 0, 0, null);
    }
    }
    }
      

  3.   

    网上找的:
    JPanel可以像网页控件一样设置背景图片,主要是通过覆写JPanel的paint(Graphics g)方法和paintComponent(Graphics g)方法; 但是二者有区别:“  JLabel类同其它的Swing组件一样,继承至javax.swing.Jcomponent.Swing。它们都是通过调用JComponent组件的paint方法来画界面。我们可以通过重载JComponent的公开方法paint来修改一个组件画界面的行为。下面是一个JComponent的paint方法的定义。    
       
      public   void   paint(Graphicsg)    
       
      作为paint方法的参数传进来的对象Graphics是一个绘图面板。为了优化绘图这个操作,paint方法被分割成三个具有保护(protected)属性的方法:paintComponent,   paintBorder,   paintChildren。paint方法调用这三个方法同时将它接受到的Graphics实例传递给这三个方法。  
       
      根据以上所说的,如果你想重画SWING的外观话就应该根据你要画的内容选择到底是重写paintComponent或paintBorder或paintChildren方法。如果同时重写了paint与paintComponent方法的话,则只会调用paint方法,而不执行paintComponent了。 ”所以:通用的添加背景的方法可以是:protected void paint(Graphics g) {
      try {
       BufferedImage img = ImageIO.read(My_Auditor_JPanel.class.getResource("/images/aa.jpg"));
       g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
      } catch (IOException e) {
       e.printStackTrace();
      }
     }和: protected void paintComponent(Graphics g) {
      try {
        BufferedImage img = ImageIO.read(My_Auditor_JPanel.class.getResource("/images/aa.jpg"));
       g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
      } catch (IOException e) {
       e.printStackTrace();
      }
     }//但是推荐第二种方法;否则第一种方法可能导致背景图片遮盖住面板的其他控件。//第二种覆写 paintComponent(Graphics g)则不会!