1

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);
     }

   }
}

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

still nothing. Its not even executed :(
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.