views:

23

answers:

2

Hi everyone,

Im trying to build a small frame that displays an image.

My problem is that in the paint(Graphics g) method, the g.drawImage is executed, but nothing is shown on my RLFrame.

Any thoughts / tips?

Thanks in advance.

Here's the code

public class RLFrame extends JFrame{

 Image img;
 public RLFrame(String title){
  super("testing");
 }
 public  void run(){
  MediaTracker mt = new MediaTracker(this);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setSize(400, 400);

  this.img = Toolkit.getDefaultToolkit().getImage("maps/23bis.ppm");
  mt.addImage(this.img, 1, 100, 100);
  this.setVisible(true);
 }


 public void paint(Graphics g){
  System.out.println("Paint");
     if(img != null){
      System.out.println("draw");
       g.drawImage(img, 300,  300, this);
     }
     else
     {
       g.clearRect(0, 0, getSize().width, getSize().height);
     }

   }
}
+1  A: 

Use paintComponent(Graphics g) instead of paint(Graphics g) in your code. Something like

protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println("Paint");
        if (img != null) {
            System.out.println("draw");
            g.drawImage(img, 300, 300, this);
        }
        else
        g.clearRect(0, 0, getSize().width, getSize().height);
 }


Add the image to a JPanel, then add that JPanel instance to your RLFrame.

Zaki
still nothing. Its not even executed :(
Tom
There we go :D Thanks.
Tom
+1  A: 

You should never overrid the paint() method of a JFrame.

There is no need for you to do custom painting. Just create an ImageIcon and add it to a JLabel, then add the label to the frame.

Check out the section from the Swing tutorial on How to Use Icons. If you really need to do custom painting then the tutorial also has a section on custom painting.

camickr