这是我的代码:
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) {
}
@Override
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);
它的作用是当我点击框架时绘制一个圆圈。绘制一些圆圈后,当我最大化或最小化或调整框架大小时,圆圈消失。我怎么解决呢?
答案 0 :(得分:7)
您应该覆盖面板的paintComponent()方法。圆圈应添加到列表中。在paintComponent()中调用super,然后遍历列表绘制每个圆圈。