1

这是我的简单代码,它在鼠标光标附近绘制椭圆。每次单击框架都会重新绘制,并且一次只能绘制一个椭圆。我想知道如何使单击时绘制的每个椭圆保持在框架上。谢谢每个建议。

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Buffer extends JPanel implements MouseListener{
public static JFrame frame;
public static boolean check;

public void paintComponent(Graphics g){
    super.paintComponent(g);
    if(check==true){
        g.drawOval((int)MouseInfo.getPointerInfo().getLocation().getX(), (int)MouseInfo.getPointerInfo().getLocation().getY(), 10, 10);
    }
}

public static void main(String args[]){
    Buffer x=new Buffer();
    x.setBackground(Color.cyan);

    frame=new JFrame();
    frame.setSize(500,500);
    frame.addMouseListener(x);
    frame.add(x);
    frame.setVisible(true);
    }

public void mouseClicked(MouseEvent e){
    check=true;
    repaint();
    }

public void mouseEntered(MouseEvent arg0){}
public void mouseExited(MouseEvent arg0){}
public void mousePressed(MouseEvent arg0){}
public void mouseReleased(MouseEvent arg0){}
 }
4

1 回答 1

5

制作一个ArrayList代表椭圆的对象。在paintComponent中,绘制列表中的每个椭圆。在鼠标侦听器中,向列表中添加一个椭圆形。这是一个例子:

public class Buffer extends JPanel implements MouseListener {
    ...
    private List<Ellipse2D> ovals = new ArrayList<Ellipse2D>();

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        for (Ellipse2D oval : ovals)
            g2d.draw(oval);
    }

    public void mouseClicked(MouseEvent e) {
        ovals.add(new Ellipse2D.Double(e.getX(), e.getY(), 10, 10);
        repaint();
    }
}
于 2013-07-26T09:13:14.167 回答