我想在JPanel2上面加入一个图片.但是,把以上代码编译后,为什么JPanel2中仍旧没有图片呢?

解决方案 »

  1.   

    public void paintComponent(Graphics g)
                             ^^_here see it,fix it with paintComponents
      

  2.   

    在工程上点右建->addfile就OK了。
      

  3.   

    两种方法
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;public class AddSysFrame
      extends JFrame {
      ImagePanel imp = new ImagePanel();
      String imageFileName = "e:/15.jpg";
      ImageIcon m_icon = new ImageIcon(imageFileName);
      JLabel jLabelImage = new JLabel();  public AddSysFrame() {
        try {
          jbInit();
        }
        catch (Exception ex) {
          ex.printStackTrace();
        }
      }  void jbInit() throws Exception {
        setSize(460, 380);
        this.addWindowListener(new AddSysFrame_this_windowAdapter(this));
        this.getContentPane().setLayout(null);
        imp.setBounds(new Rectangle(58, 49, 274, 165));
        //jLabelImage.setText("jLabel1");
        jLabelImage.setIcon(m_icon);
        jLabelImage.setBounds(new Rectangle(61, 218, 269, 109));
        this.getContentPane().add(imp, null);
        this.getContentPane().add(jLabelImage, null);
      }  public static void main(String[] args) {
        AddSysFrame addSysFrame = new AddSysFrame();
        addSysFrame.show();
      }  void this_windowClosing(WindowEvent e) {
        System.exit(0);
      }
    }class AddSysFrame_this_windowAdapter
      extends java.awt.event.WindowAdapter {
      AddSysFrame adaptee;  AddSysFrame_this_windowAdapter(AddSysFrame adaptee) {
        this.adaptee = adaptee;
      }  public void windowClosing(WindowEvent e) {
        adaptee.this_windowClosing(e);
      }
    }
    import java.awt.*;
    import javax.swing.JPanel;
    import javax.swing.*;
    import java.awt.image.BufferedImage;public class ImagePanel
      extends JPanel {
      BorderLayout borderLayout1 = new BorderLayout();
      String imageFileName = "e:/15.jpg";
      ImageIcon m_icon = new ImageIcon(imageFileName);  Image m_image = m_icon.getImage();  public ImagePanel() {
        try {
          jbInit();
        }
        catch (Exception ex) {
          ex.printStackTrace();
        }
      }  void jbInit() throws Exception {
        this.setLayout(borderLayout1);
        this.paintComponent(null);
      }  public void paintComponent(Graphics g) {
        if (g == null) {
          return;
        }
        super.paintComponent(g);
        if (m_image == null) {
          return;
        }
        g.drawImage(m_image, 0, 0, m_icon.getIconWidth(), m_icon.getIconHeight(), null);
      }
    }
      

  4.   

    推荐用 JLabel, 不要自己写 JPanel 子类