在jpanel上画图片
public class Panel1 extends JPanel{
............
URL url = getClass().getResource("pic.jpg");
      img = createImage( (ImageProducer) url.getContent());
........
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}}在JFRAME中设置ContentPane为Panel1 public class Frame1 extends JFrame {
  JPanel contentPane;
..........
public Frame1() {
.........    
jbInit();
}
private void jbInit() throws Exception  {
    this.setContentPane(new Panel1());
    contentPane=(JPanel)this.getContentPane();
    contentPane.setLayout(null);
.........
    contentPane.add(jButton1, null);
    contentPane.add(jButton2, null);
}
  
.....
}
主要的就这样,请指点。另外运行时间我发现好象重画很多次,因为看到窗口在抖发。

解决方案 »

  1.   

    private void jbInit() throws Exception  {
        this.setContentPane(new Panel1());<------------------------------问题
        contentPane=(JPanel)this.getContentPane();
        contentPane.setLayout(null);
    .........
        contentPane.add(jButton1, null);
        contentPane.add(jButton2, null);
    }
      
    在你按下按钮时,就触发了
    public void paint(Graphics g)
    {
    g.drawImage(img,0,0,this);
    }你的方法不太好,我可不加背景的。你可以把图片放在panel1中,而jButton1,jButton2放丰panel2中。如下:public class Frame1 extends JFrame {
        JPanel jPanel1 = new JPanel();
        JPanel jPanel2 = new JPanel();
        JButton jButton1 = new JButton();
        JButton jButton2 = new JButton();    public Frame1() {
            try {
                jbInit();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
            Frame1 frame1 = new Frame1();
        }
        private void jbInit() throws Exception {
            jButton1.setText("jButton1");
            jButton2.setText("jButton2");
            this.getContentPane().add(jPanel1, BorderLayout.CENTER);
            this.getContentPane().add(jPanel2,  BorderLayout.SOUTH);
            jPanel2.add(jButton2, null);
            jPanel2.add(jButton1, null);
        }
    }