paintComponent maxing out CPU

I'm currently developing a program which outputs some basic graphics, only problem is is it maxing out my CPU in the process and was just wondering why.

I have a main JFrame which instantiates a few other classes that extend JPanel. Each JPanel then displays some very basic graphics or text.

If I comment out all the JPanel class calls the JFrame displays and CPU behaves normally, but of course no graphics are displayed. If I call one of the JPanels CPU activity increases dramatically.

Below is the code for one of the simpler classes. If I comment out the whole paintComponent() method the CPU runs fine, but even with the three lines left uncommented as it is shown now, the CPU runs at 100%

import java.awt.Color;

import java.awt.Graphics;

import javax.swing.BorderFactory;

import javax.swing.JPanel;

publicclass DrawXLabelextends JPanel{

int gap, pos;

public DrawXLabel(int num){

gap = 600/num;

pos = num/10;

if (pos == 0)

pos = 1;

}

publicvoid paintComponent(Graphics g){

super.paintComponent(g);

this.setBorder(BorderFactory.createEmptyBorder(5,18,5,5));

g.setColor(Color.BLACK);

/*int j = 1;

int k = 15;

for (int i=0; i<10; i++){

g.drawString(""+j, k, 10);

j = j+pos;

k = k+gap;

}*/

}

}

[1997 byte] By [thoseiona] at [2007-11-27 3:05:33]
# 1
Just checked and it appears to be this line causing the problem:this.setBorder(BorderFactory.createEmptyBorder(5,18,5,5));If I comment it out CPU runs fine, leave it in but comment everything else out CPU runs 100%! Anyone know why and have a way around it?
thoseiona at 2007-7-12 3:51:11 > top of Java-index,Java Essentials,Java Programming...
# 2
Set the Border outside of the painting method. There's no reason to set the Border more than once, so do it in the constructor and leave it. Painting code can be called many times in a short period of time, so don't do anything in it that doesn't need to be done many times.
hunter9000a at 2007-7-12 3:51:11 > top of Java-index,Java Essentials,Java Programming...
# 3
Your a star mate, thanks! I didn't really think about the drawing methods being called more than once - guess it makes sense seeing as it has to continually update the screen.Cheers.
thoseiona at 2007-7-12 3:51:11 > top of Java-index,Java Essentials,Java Programming...