This is my code:
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel1 = new JPanel(){
@Override
protected void paintComponent(Graphics g) {
int w = getWidth();
int h = getHeight();
for (int i = 0; i < w; i+=100) {
g.drawLine(i, 0, i, h);
}
}
};
panel1.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Overri开发者_如何转开发de
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseClicked(MouseEvent arg0) {
int x = arg0.getX();
int y = arg0.getY();
Graphics g = (Graphics) panel1.getGraphics();
g.setColor(Color.black);
g.fillOval(x, y, 100, 100);
}
});
frame.add(panel1);
frame.setVisible(true);
What it does is when i click on frame a circle is drawn. after drawing some circles when i maximize or minimize or resize my frame the circles gets disappeared. how can I solve it?
You should override paintComponent() method of the panel. The circles should be added in a list. In the paintComponent() call super and then iterate through the list painting each circle.
精彩评论