I have this simple application in which a command like RECT 10 20 100 150 draws a rectangle with specified arguments on a DrawPanel(extends JPanel).
Also, after drawing the primitive, it adds it to List<String> cmdList;, so that in
paintComponent(Graphics g) of DrawPanel I iterate through the list, process each command, and draw each of them.
The problem I am facing is that after drawing few shapes, and resizing (or maximizing) the panel becomes empty. And on resizing again several times, all the shpaes get drawn correctly.
This is the screenshot after drawing few primitives.

After stretching window slightly to left, the primitives are gone.

The code for DrawPanel
public class DrawPanel extends JPanel {
private List<String> cmdList;
public final Map<String,Shape> shapes;
public DrawPanel()
{
shapes = new HashMap<String,Shape>();
shapes.put("CIRC", new Circ());
shapes.put("circ", new Circ());
shapes.put("RECT", new Rect());
shapes.put("rect", new Rect());
shapes.put("LINE", new Line());
//... and so on
cmdList = new ArrayList<String>();
}
public void addCmd(String s)
{
cmdList.add(s);
}
public void removeCmd()
{
cmdList.remove(cmdList.size());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.BLACK);
for (int i = 0; i < cmdList.size(); ++i){
StringTokenizer cmdToken = new StringTokenizer(cmdList.get(i));
String cmdShape = cmdToken.nextToken();
int []args = new int[cmdToken.countTokens()];
for(int i1 = 0; cmdToken.hasMoreTokens(); i1++){
args[i1] = Integer.valueOf(cmdToken.nextToken());
}
shapes.get(cmdShape).draw(this, args);
}
}
public void getAndDraw(String cmdShape, int[] args)
{
shapes.get(cmdShape).draw(this, args);
}
public void rect(int x1, int y1, int width, int height)
{
Graphics g = getGraphics();
g.setColor(Color.BLUE);
g.drawRect(x1, y1, width, height);
}
public void circ(int cx, int cy, int radius)
{
Graphics g = getGraphics();
g.setColor(Color.CYAN);
g.drawOval(cx - radius, cy - radius, radius*2, radius*2);
}
}
The partial code for Shape (Interface)
public interface Shape {
void draw(DrawPanel dp, int[] data);
}
class Rect implements Shape {
public void draw(DrawPanel dp, int[] data) {
dp.rect(data[0], data[1], data[2], data[3]);
}
}
Lines used in MainFrame (extends JFrame) to draw after each command is entered.
drawPanel.getAndDraw(cmdShape, args);
drawPanel.addCmd(cmd);
Why is Drawing panel, sometimes painting and other time not, on window resize?
How can I get stable output?
Note : If I have missed anything, please ask.
It’s because your using getGraphics() when you should be using the Graphics object passed as an argument to paintComponent.
Oh, and btw, setBackground(Color.BLACK) should be in the constructor, not in the paintComponent method.