当鼠标点击时,java绘制一个圆圈

前端之家收集整理的这篇文章主要介绍了当鼠标点击时,java绘制一个圆圈前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个程序,当点击鼠标时,将绘制一个圆圈.到目前为止我写的下面的代码.
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.event.*;
import java.awt.geom.*;

public class test extends JFrame implements ActionListener,MouseListener {
    Shape circle = new Ellipse2D.Float(10,10,10);

    public test () {
        setSize(250,150);
        addMouseListener(this);
    }

    public static void main(String[] args) {
        //TODO code application logic here
        java.awt.EventQueue.invokeLater(new Runnable() {
              public void run() {
                   test frame = new test();
                   frame.setVisible(true);
              }
        });
    }

    public void actionPerformed(ActionEvent ae) {

    }

    public void drawCircle(int x,int y) {
        Graphics g = this.getGraphics();
        g.drawOval(x,y,x,y);
        g.setColor(Color.BLACK);
        g.fillOval(x,2,2);
    }

    public void mouseClicked(MouseEvent e) {
        drawCircle(e.getX(),e.getY());
        repaint();
    }

    public void mouseExited(MouseEvent e) {

    }

    public void mousePressed(MouseEvent e) {

    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }
}

代码是一个400X400的jframe,当点击打开时会在半秒显示一个圆圈,问题是,当我释放鼠标时,圆圈消失了.为什么?

解决方法

将鼠标单击(…)更改为:
int x,y;

public void mouseClicked(MouseEvent e) {
    x = e.getX();
    y = e.getY();

    repaint();
}

覆盖油漆(…):

@Override
public void paint(Graphics g) {
    drawCircle(x,y);
}

猜你在找的Java相关文章