程序结构很简单,主窗口JFrame,上面有一个NormPanel(派生自JPanel),NormPanel上显示一张jpg图,但现在虽然能编译通过,但初始时NormPanel上什么也没有,必须强制刷新窗口(如先最小化再恢复,或直接最大化)才能显示jpg。看了半天,没弄明白,请各位帮忙看看。代码如下(运行时当前目录下需有一个名为test.jpg的文件):import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class PanelTest extends JFrame {
   private static String IMAGE_NAME = "test.jpg";   private static int FRAME_X = 150, FRAME_Y = 200,
    FRAME_WIDTH = 530, FRAME_HEIGHT = 286;   private JPanel normPanel;   static public void main(String args[]) {
      PanelTest app = new PanelTest();
      app.show();
   }
   
   public PanelTest() {
normPanel = new NormPanel(IMAGE_NAME);
Container c = getContentPane();
c.add(normPanel);      setBounds(FRAME_X, FRAME_Y, FRAME_WIDTH, FRAME_HEIGHT);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   public void paint(Graphics g) {
      super.paint(g);
      Insets insets = getInsets();
      ((NormPanel)normPanel).paintIcon(g, insets.left, insets.top);
   }
}class NormPanel extends JPanel {
private String imageName = null;
private Image img = null;

public NormPanel(String imageName) {
this.imageName = imageName;
img = Toolkit.getDefaultToolkit().getImage(imageName);
}
public void paintIcon(Graphics g, int x, int y) {
super.paint(g);
g.drawImage(img, x, y, getWidth(), getHeight(), this);
}
}

解决方案 »

  1.   

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class TestPanel
        extends JFrame {
      private static String IMAGE_NAME = "tu.jpg";  private static int FRAME_X = 150, FRAME_Y = 200,
          FRAME_WIDTH = 530, FRAME_HEIGHT = 286;  private JPanel normPanel;  static public void main(String args[]) {
        TestPanel app = new TestPanel();
        app.show();
      }  public TestPanel() {
        Insets insets = getInsets();
        normPanel = new NormPanel(IMAGE_NAME, insets.left, insets.top);
        Container c = getContentPane();
        c.add(normPanel);    setBounds(FRAME_X, FRAME_Y, FRAME_WIDTH, FRAME_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
    }class NormPanel
        extends JPanel {
      private String imageName = null;
      private Image img = null;
      private int x, y;  public NormPanel(String imageName, int x, int y) {
        this.imageName = imageName;
        this.x = x;
        this.y = y;
        img = Toolkit.getDefaultToolkit().getImage(imageName);
      }  public void paint(Graphics g) {
        super.paint(g);
        g.drawImage(img, x, y, getWidth(), getHeight(), this);
      }
    }
      

  2.   

    我也知道你给出的方法可以,但是可否解释我的code为什么会有我所说的问题?因为JPanel自动调用paint方法,而我的code没有实现paint方法?
      

  3.   

    to mq612(理想):
    但是,我已经在主窗口的paint方法中添加了对panel的paintIcon方法的调用了呀?
    JComponent里面paintChildren作了什么不一样的处理使得调用paint方法可以正确绘制panel,而直接在父窗体的paint方法中调用paintIcon却不行呢?