Solved

load a background image to a JFrame ...

Posted on 2004-10-03
20
572 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
 
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
bigHeights  challenge 13 55
countHi challenge 25 84
allStar challenge 1 41
HSSFWorkbook cannot be resolved error 10 15
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
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 will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

707 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now