Nathan Sacket Nathan Sacket - 5 months ago 7x
Java Question

Drawing with paintComponent in Applet Upon Event

I'm trying to create an applet that will produce as many ovals as the number specified within a textbox. The textbox appears, but upon hitting enter, my paintComponent does not draw. Thank you in advance.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import net.miginfocom.layout.*;
import net.miginfocom.swing.MigLayout;
import java.awt.geom.*;

public class OvalDrawer extends JApplet
private JLabel numberL;
private JTextField numberTF;

private NumHandler numHandler;

public static final int WIDTH = 500;
public static final int HEIGHT = 500;

//Create Layout
public void init()
setLayout(new MigLayout("wrap 2"));
numberL = new JLabel("Enter number of ovals to draw:");
numberTF = new JTextField(7);


numHandler = new NumHandler();

setSize(500, 500);

//Event Handler
public class NumHandler implements ActionListener
public void actionPerformed(ActionEvent e)


//Draw Ovals
public void paintComponent (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;


A JApplet class does not have a paintComponent method to override. Note that your compiler won't let you call the actual super method (you think you may be doing this, but you're actually calling super.paintComponents(...), a completely different method).

A bad solution is to override the JApplet's paint method, but I strongly advise you not to do this. Instead you should draw in the paintComponent method of a JPanel and then have the JApplet display that JPanel. Also, you'll want to get into the habit of using the @Override annotation to be sure that you're actually overriding methods you think are.