Solved

load a background image to a JFrame ...

Posted on 2004-10-03
20
578 Views
Last Modified: 2010-05-18
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
Comment
Question by:meow00
  • 10
  • 8
  • 2
20 Comments
 
LVL 92

Expert Comment

by:objects
ID: 12214597
0
 
LVL 1

Author Comment

by:meow00
ID: 12214616
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
 
LVL 92

Expert Comment

by:objects
ID: 12214631
paintComponent() is for JComponent's, not for JFrames.
What you have looks fine, what problems are you having with it.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 15

Expert Comment

by:Javatm
ID: 12214691
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
 
LVL 1

Author Comment

by:meow00
ID: 12214731
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
 
LVL 1

Author Comment

by:meow00
ID: 12214788
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
 
LVL 15

Expert Comment

by:Javatm
ID: 12214817
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
 
LVL 1

Author Comment

by:meow00
ID: 12215042
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
 
LVL 92

Expert Comment

by:objects
ID: 12215124
>  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
 
LVL 1

Author Comment

by:meow00
ID: 12215505
so is that possible to use a LayeredPane ... so that I can paint different layers seperately ?
0
 
LVL 92

Expert Comment

by:objects
ID: 12215518
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
 
LVL 1

Author Comment

by:meow00
ID: 12215724
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
 
LVL 92

Expert Comment

by:objects
ID: 12215771
try adding the following method:

public void update(Graphics g)
{
}
0
 
LVL 1

Author Comment

by:meow00
ID: 12215799
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
 
LVL 92

Expert Comment

by:objects
ID: 12216067
it shouldn't hasve any effect on your timer.
0
 
LVL 1

Author Comment

by:meow00
ID: 12216526
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
 
LVL 1

Author Comment

by:meow00
ID: 12223316
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
 
LVL 92

Expert Comment

by:objects
ID: 12223369
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
 
LVL 1

Author Comment

by:meow00
ID: 12223381
thanks very much ...... so where can I learn more information about the "offscreen image" ???
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 12223403
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How do I remove an object from a 3 53
Convert from a json string array to a Java object 3 64
going to wrong jsp page 2 47
import as existing maven project 3 37
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question