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;
}
}
}
}
Your
paintmethod cannot be inside youractionPerformedmethod. It needs to exist as a class member method of your component rather thanNumHandler. You could place a singlerepaint()call in yourActionListenermethod to request that a repaint be carried out.Don’t place any logic that is likely to lead to an exception in your
paintmethod, namely:This is better done in the
actionPerformedmethod.Also if using Swing,
paintComponentis preferred for optimized paint performance. Remember to callsuper.paintComponent(g);to repaint any child components.See: Painting in AWT and Swing