URGENT - JPanel Background
Hi,
I have been developing an application for my church recently and its supposed to go live tomorrow (eeeeeeeek)
but today they hit me with a enw requirement - they have to be able to set the back ground of the "Slide" so produced this code
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
publicclass SlidePaneextends JPanel
{
private String picture ="candles.png";
publicvoid setPicture(String s)
{
picture = s;
}
publicvoid paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
super.repaint();
ImageIcon img =new ImageIcon(picture);
ImageIcon img2 =new ImageIcon(img.getImage().getScaledInstance(getWidth(), getHeight(),Image.SCALE_REPLICATE));
img =null;
System.gc();
g.drawImage(img2.getImage(), 0, 0,this);
}
}
the only problem is, on my machine (which is alot higher spec than churches) it uses 100% of processor permenantly (not just loading)
it is this class that does it, and as soon as i set it to jsut use a JPanel rather than this slightly different JPanel it works fine,.
please help
# 5
Hey sorry i didnt reply sooner
was actually at work at the stdents union
i didnt mention church just to get a faster reponse no - i mentioned church because thats what its for, it s a thing to project the song words via a projector and they want touse it tommorrow evening for a thign called breathe.
talking of which if your in aberystyth, 19.00 castle rooms (under castle theatre) for 25 and unders only. be there!
cheers for the replies, i managed to figure out that it was that line of code causing the problem so i just removed. but thinking about it, i can see the issue (if so one could correct me if im wrong)
calling the repaint method causes the method, paint component to be called which then calls repaint (if coded like i did it) and there for kinda getting stuck in an infinite recursion hence eating up processor time.
if this is incorrect please tell me.
DN
# 6
> if this is incorrect please tell me.
That essentially it. It's not a direct subroutine call like:
repaint calls paint --> paint calls paintComponent -> your paintComponent calls repaint --> etc
.. because that would quickly overflow the runtime stack and you'd
get a java.lang.StackOverflowError. What happens is more subtle:
1. repaint() posts a request to repaint in the event queue
2. The Swing Event Dispatch Thread takes the event out of the
queue later, and calls paint
3. paint calls your paintComponent, which calls repaint -- back to 1.!
It's still a bad cirlcuarity, because it spins around sucking up CPU time
for no good reason.
The correct code is for paintComponent to call super.paintComponent --
this usually just erases the background, so if you forget to do it , it may
not make a big difference.