0

Sorry for a probably already solved problem, but I've searched everywhere and cannot find a solution. I've just found that no matter what, paintComponent is not called no matter where I put repaint()

I have already tried putting it in several different methods and tried to call it from different areas but no matter what, it seems to never be called.

import java.awt.*;
import java.awt.event.*;
import java.awt.Component;
import javax.swing.*;
import javax.swing.BoxLayout;
import javax.swing.event.*;
import java.awt.event.KeyEvent;
import java.util.Scanner;
public class LevelOne extends JPanel implements KeyListener
{
        int width = 0;
        int height = 0;
        int bx = 0;
        int hx = 0;
        int by = 0;
        int hy = 0;
Image joe = new ImageIcon("upgrademan.png").getImage();
        ImagePanel2 panel2 = new ImagePanel2(new ImageIcon("levelone.png").getImage());
        JFrame frame = new JFrame ("Level One");


        public LevelOne()
        {
            frame.getContentPane().add(panel2);
            Game game1 = new Game();
            frame.setSize(600, 600);


          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBackground(Color.WHITE);
      frame.pack();
            frame.setVisible(true);
            levelOne();
            requestFocus();
        }

    public void levelOne()
    {
      repaint(); // this doesn't call paintComponent below?
    }

   public void paintComponent(Graphics g)
   {
    super.paintComponent(g);       //draw background color
    System.out.println("this enters paintComponent");
    g.drawImage(joe,100,100,200,200, null);  // this doesn't seem to be drawing
    requestFocus();

    }
    public void keyPressed(KeyEvent e) // all they keyListener  methods
    {
    }
    public void keyTyped(KeyEvent e)
    {

    }
    public void keyReleased(KeyEvent e)
    {

    }

  }
  class ImagePanel2 extends JPanel {            // this entire class simply exists to call in order to set a picture as a background

     Image img;

    public ImagePanel2(String img) {        // just sets img in method to class img variable
        this(new ImageIcon(img).getImage());
    }

    public ImagePanel2(Image img) {     // sets size of picture
        this.img = img;
        Dimension dims = new Dimension(600,600);
        setPreferredSize(dims);
        setMinimumSize(dims);
        setMaximumSize(dims);
        setSize(dims);
        setLayout(null);

    }

    public void paintComponent(Graphics g) {        // draws image
        g.drawImage(img, 0, 0, this);
    }
  }

I expected the ImagePanel class to print a background, which it did, but I also expected the image called joe to print, which it did not.

1 Answers1

1

The only place you display "joe" is in the paintComponent() method of instances of LevelOne. But you never add a LevelOne instance to your frame, or to any panel in that frame.

FredK
  • 4,094
  • 1
  • 9
  • 11