• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 587
  • Last Modified:

load a background image to a JFrame ...

Hi experts,

  How do I load a background image (which won't be deleted every time I repaint) to my JFrame ???
 P.S. I already use setLayout(null) ;

  many thanks !!!

0
meow00
Asked:
meow00
  • 10
  • 8
  • 2
1 Solution
 
meow00Author Commented:
thanks object ..... so what if I already use paint() ...... can I still use paintComponent ???
The following is my test code .... I don't want to paint the background at each time step (it will cover some other texts in the future)... is that possible ?

many many thanks !!!

import javax.swing.*;
import java.awt.* ;
import java.awt.event.* ;

public class MyTest extends JFrame implements KeyListener, ActionListener{
   
    private int snake_x[] = new int[150] ;
    private int snake_y[] = new int[150] ;
    private int snake_dir[] = new int[150] ;
    private final int Delta_x = 20, Delta_y = 20 ;
   
    private static final int UP = 0 ;
    private static final int RIGHT = 1 ;
    private static final int DOWN = 2 ;
    private static final int LEFT = 3 ;
   
   
 
   
    private javax.swing.Timer headTimer ;
   
    ImageIcon headImg = new ImageIcon(getClass().getResource("head.gif"));

    public MyTest() {
        snake_x[0] = 200 ; snake_y[0] = 200 ; snake_dir[0] = 3 ;
       
        addKeyListener(this);

        headTimer = new Timer(200, this);
        headTimer.start();
       
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        setSize(600,600) ;
        show() ;
       
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        MyTest mySnake = new MyTest() ;
        // TODO code application logic here
    }
   
 
   
    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawImage( headImg.getImage(), snake_x[0], snake_y[0], 20, 20, null) ;  
   
    }

    public void actionPerformed(ActionEvent e) {
         if ( snake_dir[0] == 0) snake_y[0] -= Delta_y ;
         if ( snake_dir[0] == 1) snake_x[0] += Delta_x ;
         if ( snake_dir[0] == 2) snake_y[0] += Delta_y ;
         if ( snake_dir[0] == 3) snake_x[0] -= Delta_x ;
         repaint() ;
    }
   
    public void keyPressed(KeyEvent e) {
 
           if (e.getKeyCode()==KeyEvent.VK_UP) {
             snake_dir[0] = 0 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_RIGHT) {
             snake_dir[0] = 1 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_DOWN) {
             snake_dir[0] = 2 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_LEFT) {
             snake_dir[0] = 3 ;
           }      
         
    }
   
    public void keyReleased(KeyEvent e) {
    }
   
    public void keyTyped(KeyEvent e) {
    }
   
}

0
 
objectsCommented:
paintComponent() is for JComponent's, not for JFrames.
What you have looks fine, what problems are you having with it.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
JavatmCommented:
How do I load a background image (which won't be deleted every time I repaint) to my JFrame ???

The easiest thing to do is just to add an image to a JPanel and put it in the center of your frame. Then
add all your components =-)

import java.awt.*;
import javax.swing.*;

public class display extends JFrame {

  public display() {
 
  super("Example . . .");

  JPanel p1 = new JPanel();

  ImageIcon i1 = new ImageIcon("C:/YourFolder/YourImage.jpg");
  JLabel l1 = new JLabel();
  l1.setIcon(i1);

  p1.setLayout(new GridLayout(1,1));
  p1.add(l1);

  this.getContentPane().add(p1, BorderLayout.CENTER);
  setSize(300, 300);
  setVisible(true);  
  }

  public static void main(String args[]) {
  display x = new display();
  }
}
0
 
meow00Author Commented:
Hi,

  here is what I try to do ....
  under head.gif .. I added

  "ImageIcon bgImg = new ImageIcon(getClass().getResource("background1.gif"));"

  also in the paint(), I added :
   " g.drawImage( bgImg.getImage(), 0, 0, 420, 420,  null) ;"

  in order to make a background .... then I ran into the following problems :

 1. because the background is painted every time step, so it cover some texts ... and I saw flashs on the screen ....
 2. it seems a waste of time to paint a never changed background ....

  therefore, I am wondering is that possible to paint it just once at the very beginning ???

  thanks very much !!!
0
 
meow00Author Commented:
Hi JavaTM,

   thanks for the info ..... since I already use setLayout(null) to add other components ... can I still use the above methods ??? can I change back to setLayout(null) after I add the background ???

 thanks !!!
0
 
JavatmCommented:
Yes;

You can also try this :

    public class MyFrame extends JFrame {

        public MyFrame() {

            //  Set the background image . . .
        URL url = MyFrame.class.getResource( "background.gif" );
        Image image = Toolkit.getDefaultToolkit().createImage( url );
        ImagePanel imagePanel = new ImagePanel( image );
        setContentPane( imagePanel );

        //  Now add other components to the JFrame's content pane:
        getContentPane().setLayout( new FlowLayout() );
        getContentPane().add( new JLabel( "Testing" ) );
        getContentPane().add( new JTextField( 10 ) );

        setTitle("Example . . .");
        setSize(300, 300);
        setVisible(true);
        }

        public static void main(String args[]) {

        MyFrame x = new MyFrame();
        x.setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
    }
0
 
meow00Author Commented:
Hi JavaTM,

   I did your suggestion .... but I couldn't see my background in the first version. Also, It can not find "ImagePanel" in the second version. please help !

-------------------------------------------
import java.io.* ;
import javax.swing.*;
import java.awt.* ;
import java.awt.event.* ;
import java.net.URL;
import java.applet.*;

public class MyTest extends JFrame implements KeyListener, ActionListener{
   
    private int snake_x[] = new int[150] ;
    private int snake_y[] = new int[150] ;
    private int snake_dir[] = new int[150] ;
    private final int Delta_x = 20, Delta_y = 20 ;
   
    private static final int UP = 0 ;
    private static final int RIGHT = 1 ;
    private static final int DOWN = 2 ;
    private static final int LEFT = 3 ;
   
   
 
   
    private javax.swing.Timer headTimer ;
   
    ImageIcon headImg = new ImageIcon(getClass().getResource("head.gif"));

   
    ImageIcon burgerImg = new ImageIcon(getClass().getResource("hamburger.gif"));
    /** Creates a new instance of SnakeFrame */
 
    public MyTest() {
       
   //       URL url = MyTest.class.getResource( "background.gif" );
   //     Image image = Toolkit.getDefaultToolkit().createImage( url );
   //     ImagePanel imagePanel = new ImagePanel( image );
   //     setContentPane( imagePanel );

        //  Now add other components to the JFrame's content pane:
   //     getContentPane().setLayout( new FlowLayout() );
   //     getContentPane().add( new JLabel( "Testing" ) );
   //     getContentPane().add( new JTextField( 10 ) );

          JPanel p1 = new JPanel();

        ImageIcon i1 = new ImageIcon("background0.gif");
        JLabel l1 = new JLabel();
        l1.setIcon(i1);

        p1.setLayout(new GridLayout(1,1));
        p1.add(l1);

        this.getContentPane().add(p1, BorderLayout.CENTER);
 
        snake_x[0] = 200 ; snake_y[0] = 200 ; snake_dir[0] = 3 ;
       
        addKeyListener(this);

        headTimer = new Timer(200, this);
        headTimer.start();
       
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        setSize(600,600) ;
        show() ;
       
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        MyTest mySnake = new MyTest() ;
        // TODO code application logic here
    }
   
 
   
    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawImage( headImg.getImage(), snake_x[0], snake_y[0], 20, 20, null) ;  
   
    }

    public void actionPerformed(ActionEvent e) {
         if ( snake_dir[0] == 0) snake_y[0] -= Delta_y ;
         if ( snake_dir[0] == 1) snake_x[0] += Delta_x ;
         if ( snake_dir[0] == 2) snake_y[0] += Delta_y ;
         if ( snake_dir[0] == 3) snake_x[0] -= Delta_x ;
         repaint() ;
    }
   
    public void keyPressed(KeyEvent e) {
 
           if (e.getKeyCode()==KeyEvent.VK_UP) {
             snake_dir[0] = 0 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_RIGHT) {
             snake_dir[0] = 1 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_DOWN) {
             snake_dir[0] = 2 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_LEFT) {
             snake_dir[0] = 3 ;
           }      
         
    }
   
    public void keyReleased(KeyEvent e) {
    }
   
    public void keyTyped(KeyEvent e) {
    }
   
}

0
 
objectsCommented:
>  1. because the background is painted every time step, so it cover some texts ... and I saw flashs on the screen ....

you should be painting the background *before* you paint the text.

> 2. it seems a waste of time to paint a never changed background ....

it still needs to get repainted, for example if the frame gets obscured by another window.

> I am wondering is that possible to paint it just once at the very beginning ???

no it needs to be painted whenever the component needs painting.
0
 
meow00Author Commented:
so is that possible to use a LayeredPane ... so that I can paint different layers seperately ?
0
 
objectsCommented:
you can paint the image on whatever component you want, but if you want it to appear as the background then the layered pane would not be appropriate.
0
 
meow00Author Commented:
Hi,

    Thanks very much for the info.... so would there be a way to fix the "flash" problem in the following code ??? (The screen keeps flashing !) or what would be the best way to deal with this kind of problem ??? ( How do people deal with a constant background + changed foreground in Java ???)

    many many thanks !!!
-----------------------------------------------------------------------------------------

import java.io.* ;
import javax.swing.*;
import java.awt.* ;
import java.awt.event.* ;
import java.net.URL;
import java.applet.*;

public class MyTest extends JFrame implements KeyListener, ActionListener{
   
    private int snake_x[] = new int[150] ;
    private int snake_y[] = new int[150] ;
    private int snake_dir[] = new int[150] ;
    private final int Delta_x = 20, Delta_y = 20 ;
   
    private static final int UP = 0 ;
    private static final int RIGHT = 1 ;
    private static final int DOWN = 2 ;
    private static final int LEFT = 3 ;

    private javax.swing.Timer headTimer ;  
    ImageIcon headImg = new ImageIcon(getClass().getResource("head.gif"));

     ImageIcon bgImg = new ImageIcon(getClass().getResource("background0.gif"));
     
    public MyTest() {
         
        snake_x[0] = 200 ; snake_y[0] = 200 ; snake_dir[0] = 3 ;
       
        addKeyListener(this);

        headTimer = new Timer(200, this);
        headTimer.start();
       
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        setSize(600,600) ;
        show() ;
       
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        MyTest mySnake = new MyTest() ;
        // TODO code application logic here
    }
   
 
   
    public void paint(Graphics g)
    {
        super.paint(g);
          g.drawImage( bgImg.getImage(), 0, 0, 420, 420,  null) ;
        g.drawImage( headImg.getImage(), snake_x[0], snake_y[0], 20, 20, null) ;  
   
    }

    public void actionPerformed(ActionEvent e) {
         if ( snake_dir[0] == 0) snake_y[0] -= Delta_y ;
         if ( snake_dir[0] == 1) snake_x[0] += Delta_x ;
         if ( snake_dir[0] == 2) snake_y[0] += Delta_y ;
         if ( snake_dir[0] == 3) snake_x[0] -= Delta_x ;
         repaint() ;
    }
   
    public void keyPressed(KeyEvent e) {
 
           if (e.getKeyCode()==KeyEvent.VK_UP) {
             snake_dir[0] = 0 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_RIGHT) {
             snake_dir[0] = 1 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_DOWN) {
             snake_dir[0] = 2 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_LEFT) {
             snake_dir[0] = 3 ;
           }      
         
    }
   
    public void keyReleased(KeyEvent e) {
    }
   
    public void keyTyped(KeyEvent e) {
    }
   
}

0
 
objectsCommented:
try adding the following method:

public void update(Graphics g)
{
}
0
 
meow00Author Commented:
err .... after I added update() to the code ... the timer stops running ...... am I suppose to put any thing inside the update() function ? or is there any specific place I should place it ??? thanks !!!
0
 
objectsCommented:
it shouldn't hasve any effect on your timer.
0
 
meow00Author Commented:
Thanks object,

   You are right, the timer didn't stop ! But how come that my head.gif doesn't move after I press a key ?
It worked fine before I added the background ??? please help ! thanks very much !!!
-----------------------------------------------------------------------------
import java.io.* ;
import javax.swing.*;
import java.awt.* ;
import java.awt.event.* ;
import java.net.URL;
import java.applet.*;

public class SimpleTest extends JFrame implements KeyListener, ActionListener{
   
    private int snake_x[] = new int[150] ;
    private int snake_y[] = new int[150] ;
    private int snake_dir[] = new int[150] ;
    private final int Delta_x = 20, Delta_y = 20 ;
   
    private static final int UP = 0 ;
    private static final int RIGHT = 1 ;
    private static final int DOWN = 2 ;
    private static final int LEFT = 3 ;
   
    private int time_step = 0 ;
 
   
    private javax.swing.Timer headTimer ;
   
    ImageIcon headImg = new ImageIcon(getClass().getResource("head.gif"));

     ImageIcon bgImg = new ImageIcon(getClass().getResource("background0.gif"));
    ImageIcon burgerImg = new ImageIcon(getClass().getResource("hamburger.gif"));
    /** Creates a new instance of SnakeFrame */
 
    public SimpleTest() {
   
        snake_x[0] = 200 ; snake_y[0] = 200 ; snake_dir[0] = 3 ;
       
        addKeyListener(this);

        headTimer = new Timer(200, this);
        headTimer.start();
       
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        setSize(600,600) ;
        show() ;
       
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SimpleTest mySnake = new SimpleTest() ;
        // TODO code application logic here
    }
   
 
    public void update(Graphics g)
   {
   }

    public void paint(Graphics g)
    {
        super.paint(g);
          g.drawImage( bgImg.getImage(), 0, 0, 420, 420,  null) ;
        g.drawImage( headImg.getImage(), snake_x[0], snake_y[0], 20, 20, null) ;  
   
    }

    public void actionPerformed(ActionEvent e) {
        time_step ++ ;
         System.out.println(time_step) ;
         if ( snake_dir[0] == 0) snake_y[0] -= Delta_y ;
         if ( snake_dir[0] == 1) snake_x[0] += Delta_x ;
         if ( snake_dir[0] == 2) snake_y[0] += Delta_y ;
         if ( snake_dir[0] == 3) snake_x[0] -= Delta_x ;
         repaint() ;
    }
   
    public void keyPressed(KeyEvent e) {
            System.out.println("Key") ;
           if (e.getKeyCode()==KeyEvent.VK_UP) {
             snake_dir[0] = 0 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_RIGHT) {
             snake_dir[0] = 1 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_DOWN) {
             snake_dir[0] = 2 ;
           }
           else if (e.getKeyCode()==KeyEvent.VK_LEFT) {
             snake_dir[0] = 3 ;
           }      
         
    }
   
    public void keyReleased(KeyEvent e) {
    }
   
    public void keyTyped(KeyEvent e) {
    }
   
}

0
 
meow00Author Commented:
Hi Experts,

   I tried to move the code in paint() to update(). The code works now. However, the "flash" problem is still there. Is there anyway to fix it .... many thanks !!!
//--------------------------------------------
public void update(Graphics g)
   {
       super.paint(g);
        System.out.println("cat") ;
          g.drawImage( bgImg.getImage(), 0, 0, 420, 420,  null) ;
        g.drawImage( headImg.getImage(), snake_x[0], snake_y[0], 20, 20, null) ;  
   }

    public void paint(Graphics g)
   {
   //     super.paint(g);
   //     System.out.println("dog") ;
   //       g.drawImage( bgImg.getImage(), 0, 0, 420, 420,  null) ;
   //     g.drawImage( headImg.getImage(), snake_x[0], snake_y[0], 20, 20, null) ;  
   
    }
 
0
 
objectsCommented:
sorry got sidetracked, I misled you earlier update() should have called paint().
It won't fix your flashing problem though.

I'd suggest using an offscreen image to remove the flashing.
What that involves is doing your painting to an offscreen image, and then in your paint method paint that offscreen image to the screen.
0
 
meow00Author Commented:
thanks very much ...... so where can I learn more information about the "offscreen image" ???
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 10
  • 8
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now