Mouse pointer issue in Java Swing

I created the following simple Java Swing program that displays a 3 * 3 square in the window every time the user clicks. The squares remain in the window, even if the user clicks more than once. The program compiles and works just fine, however, when one click in the window, the square extends far below where the mouse pointer is located. I'm already puzzling a bit over this - what can I change here so that the square displays exactly with a pointer to each click? Thanks so much for any help!

import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.JFrame; public class ClickCloud extends JComponent { final ArrayList<Point2D> points = new ArrayList<Point2D>(); public void addPoint(Point2D a) { points.add(a); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; for (int i = 0; i < points.size(); i++) { Point2D aPoint = points.get(i); g2.draw(new Rectangle2D.Double(aPoint.getX(), aPoint.getY(), 3, 3)); } } public static void main(String[] args) { final ClickCloud cloud = new ClickCloud(); JFrame aFrame = new JFrame(); class ClickListen implements MouseListener { @Override public void mouseClicked(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent arg0) { cloud.addPoint(arg0.getPoint()); cloud.repaint(); } @Override public void mouseReleased(MouseEvent arg0) { } } aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aFrame.setSize(500, 500); aFrame.add(cloud); aFrame.addMouseListener(new ClickListen()); aFrame.setVisible(true); } } 
+4
source share
1 answer

You add a MouseListener to the JFrame, but show the results in JComponent and relative to JComponent. Thus, the click point of the point will refer to the coordinates of the JFrame, but then displayed relative to the coordinates of the JComponent, which are shifted down by the distance of the title bar. Instead, simply add a MouseListener to the same component that is responsible for displaying the results so that the displayed and sliding coordinates match:

  aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aFrame.setSize(500, 500); aFrame.add(cloud); //!! aFrame.addMouseListener(new ClickListen()); // !! Removed cloud.addMouseListener(new ClickListen()); // !! added aFrame.setVisible(true); 

By the way: thanks for creating and publishing a decent SSCCE , as this makes it easier to analyze and solve your problem.

+4
source

Source: https://habr.com/ru/post/1341933/


All Articles