Mouse Problem

javaprogrammer

New Member
28/7/20
12
0
1
Nghệ An
em đang làm một cái test về mouseListener trong java thì gặp vấn đề như sau : mỗi khi ấn lên màn hình thì đáng lẽ mỗi lần ấn thì nó phải hiện ra một hình tròn , nhưng đôi lúc phải ấn nhiều lần mới hiện ra được . Ai giải thích hộ em.

Java:
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MouseTest extends Frame implements MouseListener {
    public MouseTest() {
        addMouseListener(this);
        setSize(300, 300);
        setLayout(null);
        setVisible(true);
    }

    public void mouseClicked(MouseEvent e) {
        Graphics g = getGraphics();
        g.setColor(Color.RED);
        g.fillOval(e.getX(), e.getY(), 30, 30);
        e.consume();
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public static void main(String[] args) {
        new MouseTest();
    }
}
 

Joe

Thành viên VIP
21/1/13
2,962
1,307
113
It's NOT the Mouse problem. It's YOUR coding problem. It seems to me that you are a self-learner and therefore you are lacking of some OOPL basic knowledge.
First: if you work with the graphics the graphics should be stable all the time and NOT instantiated every time when the graphics is used. You repeat the same mistake with the MAP problem you've posted HERE.
Second: the repetitive invocation of
Java:
Graphics g = getGraphics();
is redundant and causes problems with synchronization between the main thread and the event thread. And that is the reason why the red circle is intermittently missed. And it's very, very bad for the performance.

How to solve the problem? See the solution of your MAP problem that I've shown you. It's similar...
 
Sửa lần cuối: