单击鼠标时java绘制一个圆圈 [英] java drawing a circle when mouse clicked

查看:260
本文介绍了单击鼠标时java绘制一个圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,当点击鼠标时,将绘制一个圆圈。到目前为止我写的下面的代码。

i am writing a program that when the mouse is clicked, a circle will be drawn. The below code i've wrote so far.

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, 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, y, 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,点击打开显示在半秒钟的圆圈,问题是,当我释放鼠标时,圆圈消失。为什么?

The code is a 400X400 jframe, when clicked open display a circle at a half seconds, The problem is that, when i release the mouse, the circle disappear. why?

推荐答案

mouseClick(...)更改为:

int x, y;

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

    repaint();
}

覆盖 paint(...)

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

这篇关于单击鼠标时java绘制一个圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆