Nathan Sacket
Nathan Sacket

Reputation: 117

Paint Method within an ActionListener

I am trying to use the Java paint method within an ActionListener. However, when paint is placed within the ActionListener, my compiler throws errors, and eclipse does not recognize paint as a method at all, despite importing java.awt.geom.*;

private class NumHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
              //Draw Ovals
              public void paint (Graphics g)
              {
                   int number;
                   int x = 10;
                   int y = 30;
                   int width = 20;
                   int height = 10;

                   number = Integer.parseInt(numberTF.getText());

                   for (int i = 0; i < number; i++)
                   {
                        g.drawOval(x, y, width, height);

                        x += 5;
                        y += 5;
                        width += 5;
                        height += 5;
                   }
              }
    }

}

Upvotes: 1

Views: 2571

Answers (1)

Reimeus
Reimeus

Reputation: 159754

Your paint method cannot be inside your actionPerformed method. It needs to exist as a class member method of your component rather than NumHandler. You could place a single repaint() call in your ActionListener method to request that a repaint be carried out.

Don't place any logic that is likely to lead to an exception in your paint method, namely:

number = Integer.parseInt(numberTF.getText());

This is better done in the actionPerformed method.

Also if using Swing, paintComponent is preferred for optimized paint performance. Remember to call super.paintComponent(g); to repaint any child components.

See: Painting in AWT and Swing

Upvotes: 3

Related Questions