In my gui that I have created in Java, every time I minimize the window, repaint is called and the drawing that was originally there vanishes once the window is maximized (back to normal)
So I created an action Listener to detect when the window had been minimized and then maximized for it to draw each point that was originally on the panel back to the screen.
Unfortunately, I am not getting the results that I expected.
For some reason, when the window is maximized each point is drawn back onto the panel but the background of the entire window is black. Also, this can be very annoying for the user to have to wait for each point to be drawn back onto the screen each time they want to minimize the window.
Here is what I have so far:
//Redraw plot if window is minimized
window.addWindowStateListener(new WindowAdapter()
{
Graphics g = dPanel.getGraphics();
public void windowStateChanged(WindowEvent ev)
{
boolean minimized = false;
//If user minimizes window and then maximizes window
if(window.getExtendedState() == Frame.ICONIFIED )
{
minimized = true;
System.out.println("Window minimized");
}
if(ev.getNewState() == Frame.NORMAL || minimized == true)
{
System.out.println("Window back to normal state");
//Draw each Point back onto the screen
for(Point i: PointArray)
{
drawPoint(g, i, startColor);
System.out.println("Panel Repaint");
}
}
}
});
}
Is there some way that my code can be edited to achieve the desired results or is there a better way to do this. Basically, I just want that when the user minimizes the GUI, the painting that was there before minimization is still there once the user maximizes the window. Also, moving the window around can also cause parts of the panel to be repainted or the entire panel to be repainted.
//Draws point onto panel
public void drawPoint(Graphics g, Point PointArray, Color color)
{
Graphics2D g2d = (Graphics2D)g;
g2d.setStroke(new BasicStroke(2f));
g.setColor(color); //g2d.setColor(Color.black);
g2d.drawOval((int)PointArray.a, (int)PointArray.b, 2, 2);
}
The more I read on your situation and need, the more I think you should actually use getGraphics, but do not call this on a JComponent such as a JPanel. Rather you should do your drawing in a BufferedImage, and you should get the Graphics object of the BufferedImage by calling getGraphics on the BufferedImage. You can then draw this BufferedImage in a JComponent’s paintComponent method with the Graphics#drawImage(…) method, or even better for its simplicity (and if you don’t want to use the image as a background for a JPanel or gui), draw the Image in an ImageIcon that is displayed in a JLabel. One caveat though is if you get your Graphics object in ths way, don’t forget to dispose of it when you’re done.