I can get the mouse pointer location in a JPanel by add a MouseAdapter on it. However, it only works when users move the mouse pointer or do some other operations. The code is here:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LocationTest {
public static void main(String[] args) {
LocationTest locationTest = new LocationTest();
locationTest.createUI();
}
public void createUI(){
JFrame frame = new JFrame("Location Test");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainPanel mainPanel = new MainPanel();
mainPanel.addMouseListener(new CustomMouseListener());
mainPanel.addMouseMotionListener(new CustomMouseListener());
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@SuppressWarnings("serial")
class MainPanel extends JPanel{
@Override
public Dimension getPreferredSize() {
// TODO Auto-generated method stub
return new Dimension(400,300);
}
}
class CustomMouseListener extends MouseAdapter{
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Click: " + e.getPoint().getX() + " , " + e.getPoint().getY());
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Press: " + e.getPoint().getX() + " , " + e.getPoint().getY());
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Release: " + e.getPoint().getX() + " , " + e.getPoint().getY());
}
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("Drag: " + e.getPoint().getX() + " , " + e.getPoint().getY());
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("MouseMove: " + e.getPoint().getX() + " , " + e.getPoint().getY());
}
}
}
Is it possible to get the location without any mouse operation? For example, I can use panel.getPointerLocation to get this info anytime I want.
Thank you for your help in advance.