I have Form on which i am drawing oval on mouseClick Event. This works Fine for me. The Circles are painted. But When i Minimize the Form and Again Maximize it the Panel gets Refreshed and Circles are removed (i.e Panel is left Blank).
Code is : I have a JFrame on which there is a Jpanel named jPanel1, on this panel circles are drawn.
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
count += 1;
if (count <= clients) {
drawCircle(evt.getX() - (radius / 2), evt.getY() - (radius / 2));
}
}
public void drawCircle(int x, int y) {
Graphics g = jPanel1.getGraphics();
g.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
g.setColor(Color.BLACK);
g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
}
In this case, not only is it important to override your paintComponent
method for the JPanel, but you also need to store the information about the circles you're going to draw. You use that stored information to paint all the circles on the screen during the paintComponent
call.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class TempProject extends JPanel{
/** Stores info about circles */
public ArrayList<CircleInfo> circles = new ArrayList<CircleInfo>();
/** fields that were in example code */
public int count = 0;
public final int radius = 20;
public final int clients = 20;
public TempProject(){
addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent evt) {
count += 1;
if (count <= clients) {
// Store info about the circle to draw
circles.add(new CircleInfo(evt.getX() - (radius / 2), evt.getY() - (radius / 2), radius));
// Tell swing to repaint asap
repaint();
}
}});
}
@Override
public void paintComponent(Graphics g ) {
super.paintComponent(g);
//Iterates through saved circles and paints them
for(CircleInfo circle : circles){
g.drawOval(circle.x - circle.radius, circle.y - circle.radius, 2 * circle.radius, 2 * circle.radius);
g.setColor(Color.BLACK);
g.fillOval(circle.x - circle.radius, circle.y - circle.radius, 2 * circle.radius, 2 * circle.radius);
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(new TempProject());
frame.setPreferredSize(new Dimension(400, 300));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
/** Simple class for storing Circle info */
public static class CircleInfo{
int x = 0;
int y = 0;
int radius = 0;
public CircleInfo(int x, int y, int radius){
this.x = x; this.y = y; this.radius = radius;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With