Java-repaint()替代方案

时间:2013-07-26 09:08:35

标签: java swing paintcomponent repaint

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

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){}
 }

1 个答案:

答案 0 :(得分: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();
    }
}