Skip to content
Advertisement

Press JButton to draw a ball, the ball is not visible

So, I want to draw a ball whenever the user presses JButton. My problem is that the ball is not visible after I call revalidate() and repaint(). Am I forgetting something? Here is my code, I have another class for the queue and stack that’s why I extended Queueue. My buttons are visible and I know they work when I press them, it’s jst that the ball doesn’t show up on the screen. Earlier I tried to have my void paintComponent in my ActionListener but it would not work. I then wanted to just call the method but because of the Graphics g parameter it would not work as well. So I saw similar issue where someone suggested to use boolean

JavaScript

Advertisement

Answer

You had some syntax errors which I corrected. I also trimmed it down to more clearly demonstrate the procedure. Here is a working version that just paints the ball.

JavaScript
  • Your class should extend JPanel
  • Add it to the JFrame.
  • Add the JButton to Main instance
  • and in paintComponent call super.paintComponent(g) first.

Check out The Java Tutorials for more information on how to paint.

In response to your comments, the following should work. The main issue is that you need to have the paintComponent inside a JPanel, not as a method in Queueue.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement