Search code examples
javaswingjpanelcallpaintcomponent

How to get paintComponent method to appear on screen


I am trying to get pictures to appear on a JPanel and have previously tried using JLabels but that didn't work so now I am trying to use the paintComponent method. My code consists of making a window with a frame and adding a JPanel to the frame. Then in my actionPerformed method called by using a timer calls repaint I don't receive output from the System.out.println method. Any way I can get this working?

public void createWindow(){

    frame.add(panel);
    frame.addComponentListener(this);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.pack();
    frame.setSize(xSize, ySize);
    frame.setLocation(0, 0);

    }

@Override                 
public void paintComponent(Graphics g) {

    System.out.println("Method Called");
    super.paintComponent(g);
    g.drawString("Code has painted", 10, 100);

    }

Solution

  • Your code doesn't show us the problem other than that you're not adding this to the JFrame. For the paintComponent method to be called, the object that holds the method must be added to the GUI, it must be visible. Your code doesn't show this.

    In other words, change this:

    public void createWindow(){
        frame.add(panel);  // what is panel? do you override *its* paintComponent?
        frame.addComponentListener(this);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setSize(xSize, ySize);
        frame.setLocation(0, 0);
    }
    

    to this:

    public void createWindow(){
        frame.add(this);  // ******  Here you go ****
        frame.addComponentListener(this);  // Not sure what this is for
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
        // frame.setSize(xSize, ySize); // *** avoid this guy
        frame.setLocation(0, 0);
    }
    

    Also you state:

    I am trying to get pictures to appear on a JPanel and have previously tried using JLabels but that didn't work

    But using a JLabel should work just fine and is usually the easier way to do this, especially if the image doesn't have to re-size. Consider showing us this code attempt.