如何获得鼠标指针在JPanel中的位置(不执行鼠标的任何操作)? [英] How can I get the location of the mouse pointer in a JPanel (Without any operation of the Mouse)?
本文介绍了如何获得鼠标指针在JPanel中的位置(不执行鼠标的任何操作)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过在JPanel上添加一个MouseAdapter来获得鼠标指针的位置.但是,它仅在用户移动鼠标指针或执行某些其他操作时才有效.代码在这里:
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());
}
}
}
是否可以在没有任何鼠标操作的情况下获取位置?例如,我可以随时使用panel.getPointerLocation获取此信息.
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.
谢谢您的帮助.
推荐答案
使用MouseInfo.getPointerInfo().getLocation()随时获取当前鼠标位置.
Use MouseInfo.getPointerInfo().getLocation() to get the current mouse position at any time.
这篇关于如何获得鼠标指针在JPanel中的位置(不执行鼠标的任何操作)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文