I have painted a panel but when the program starts panel shows with delay. what should I do?
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(ResourceLoader.class.getResource("wood3.jpg"));
@Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
int width = getWidth();
int height = getHeight();
Graphics2D graphics = (Graphics2D) g;
graphics.setStroke(new BasicStroke(1));
graphics.drawImage(img, 0, 0, width, height, null, null);
this.updateUI();
repaint();
}
You are calling repaint()
inside paintComponent(Graphics g)
function: you understand that it is going to be a recursive painting-stack(request) call. Try printing a string inside your code and set your eyes on the console.
Use a Thread to read the image and let the swing run in EDT using SwingUtilities.invokeLater(Runnable)
. That way you won't have to await your application for the image to load.
As MadProgrammer has suggested, use Graphics.drawImage(x, y, width, height, ImageObserver)
function. Try to set this
as the Observer instead of null
. @AndrewThompson had an example to show the usecase of ImageObserver
. i have forgot the link however :P