Java 怎么获取鼠标当前的(jpanel)位置!鼠标是移动会发生变化!请给出代码谢谢

 我来答
百度网友528748c
2012-04-19
知道答主
回答量:8
采纳率:0%
帮助的人:3.9万
展开全部
代码如下:
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class MouseHelp extends javax.swing.JPanel implements MouseMotionListener {
private JButton textButton;
Robot robot;
/**
* Auto-generated main method to display this
* JPanel inside a new JFrame.
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MouseHelp());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

public MouseHelp() {
super();
initGUI();
}

private void initGUI() {

try {
robot=new Robot();
addMouseMotionListener(this);
setPreferredSize(new Dimension(400, 300));
this.setLayout(null);
{
textButton = new JButton();
this.add(textButton);
textButton.setText("\u8fd0 \u884c");
textButton.setBounds(136, 72, 127, 22);
textButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {
robot.mouseMove(30,745);
try {
Thread.sleep(1000);
robot.mousePress(MouseEvent.BUTTON1_MASK);
robot.mouseRelease(MouseEvent.BUTTON1_MASK);
Thread.sleep(1000);
robot.mouseMove(150,481);
robot.mousePress(MouseEvent.BUTTON1_MASK);
robot.mouseRelease(MouseEvent.BUTTON1_MASK);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}});
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub

}

public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
//从这里获取鼠标的全局坐标
Point mousepoint = MouseInfo.getPointerInfo().getLocation();
System.out.println(mousepoint.x+"\t"+mousepoint.y);
}

}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式