我可以通过在其上添加MouseAdapter来获取JPanel中的鼠标指针位置。但是,它仅在用户移动鼠标指针或执行其他操作时才有效。代码在这里:
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随时获取此信息。
提前感谢您的帮助。
答案 0 :(得分:3)
使用MouseInfo.getPointerInfo()。getLocation()随时获取当前鼠标位置。
答案 1 :(得分:0)
定义一个新界面,以便监听器可以向面板提供反馈:
public interface PointHolder {
/**
* Pass the new mouse location.
* Pass null if the mouse left the panel
*/
public void setPoint(Point newpoint);
}
让MainPanel实现它:
public MainPanel extends JPanel implements PointHolder {
private Point lastpoint;
@Override
public void setPoint(Point newpoint) {
lastpoint=newpoint;
}
public Point getPointerLocation() {
return lastpoint;
}
}
向CustomMouseListener添加构造函数:
public CustomMouseListener {
PointHolder holder;
public CustomMouseListener(PointHolder holder) {
this.holder=holder;
}
@Override
public void mouseMoved(MouseEvent e) {
holder.setPoint(e.getPoint());
System.out.println("MouseMove: " + e.getPoint().getX() + " , " + e.getPoint().getY());
}
@Override
public void mouseExited(MouseEvent e)
{
holder.setPoint(null);
}
}
在你的主要:
MainPanel mainPanel = new MainPanel();
CustomMouseListener listener=new CustomMouseListener(mainPanel);
mainPanel.addMouseListener(listener);
mainPanel.addMouseMotionListener(listener);
从现在开始,您可以调用mainPanel.getPointerLocation()
,如果鼠标不再位于面板上,则应返回null。