I experienced a similar problem to Sameer Khazi in his original post.
I realised that the code I provided is used together with another class.
The class that extends JPanel is called each time a user clicks a button. This other class
creates a JFrame, creates a button, adds a listener to the button, creates a panel, adds the button and panel to the frame,
and when the user clicks on the button, the code in the actionPerformed method is executed, which in
this case is frame.repaint(). This causes the paintComponent method to be called. I did not need to add a
main method to the original code I posted.
Thanks for the reply.