java怎么让按钮跟着鼠标移动
用JC编写,怎么能让按钮一直跟着鼠标,一直甩不掉,然后怎么能让鼠标点住这个按钮的时候,显示鼠标当前坐标,要最简单的写法,谢谢高手指教!!!!!!一定要给我看代码,谢谢啦!...
用JC编写,怎么能让按钮一直跟着鼠标,一直甩不掉,然后怎么能让鼠标点住这个按钮的时候,显示鼠标当前坐标,要最简单的写法,谢谢高手指教!!!!!!
一定要给我看代码,谢谢啦! 展开
一定要给我看代码,谢谢啦! 展开
2个回答
展开全部
前提:你容器使用的布局需要null,这样你容器上其它组件都需要自己控制大小和位置了。
问题:你需要显示的鼠标坐标是基于屏幕还是容器还是窗口还是按钮?
给你个简单的显示鼠标基于窗口坐标的例子,鼠标坐标显示在窗口标题栏上。
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TraceMouse extends JFrame{
JButton btnTrace;
boolean showMousePosition;
Insets insets;
public TraceMouse(){
setSize(640,480);
setLayout(null);
btnTrace=new JButton("点我显示鼠标坐标");
btnTrace.setSize(btnTrace.getPreferredSize());
add(btnTrace);
btnTrace.addMouseMotionListener(new MouseMotionListener(){
public void mouseDragged(MouseEvent e){
Point position=getMousePosition();
btnTrace.setLocation(position.x-insets.left-btnTrace.getWidth()/2,position.y-insets.top-btnTrace.getHeight()/2);
TraceMouse.this.setTitle(String.format("当前鼠标坐标为:(%1$d,%2$d)",position.x,position.y));
}
public void mouseMoved(MouseEvent e){
Point position=getMousePosition();
btnTrace.setLocation(position.x-insets.left-btnTrace.getWidth()/2,position.y-insets.top-btnTrace.getHeight()/2);
}
});
addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e){
Point position=getMousePosition();
btnTrace.setLocation(position.x-insets.left-btnTrace.getWidth()/2,position.y-insets.top-btnTrace.getHeight()/2);
}
});
setVisible(true);
insets=getInsets();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public static void main(String[] args){
new TraceMouse();
}
}
问题:你需要显示的鼠标坐标是基于屏幕还是容器还是窗口还是按钮?
给你个简单的显示鼠标基于窗口坐标的例子,鼠标坐标显示在窗口标题栏上。
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TraceMouse extends JFrame{
JButton btnTrace;
boolean showMousePosition;
Insets insets;
public TraceMouse(){
setSize(640,480);
setLayout(null);
btnTrace=new JButton("点我显示鼠标坐标");
btnTrace.setSize(btnTrace.getPreferredSize());
add(btnTrace);
btnTrace.addMouseMotionListener(new MouseMotionListener(){
public void mouseDragged(MouseEvent e){
Point position=getMousePosition();
btnTrace.setLocation(position.x-insets.left-btnTrace.getWidth()/2,position.y-insets.top-btnTrace.getHeight()/2);
TraceMouse.this.setTitle(String.format("当前鼠标坐标为:(%1$d,%2$d)",position.x,position.y));
}
public void mouseMoved(MouseEvent e){
Point position=getMousePosition();
btnTrace.setLocation(position.x-insets.left-btnTrace.getWidth()/2,position.y-insets.top-btnTrace.getHeight()/2);
}
});
addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e){
Point position=getMousePosition();
btnTrace.setLocation(position.x-insets.left-btnTrace.getWidth()/2,position.y-insets.top-btnTrace.getHeight()/2);
}
});
setVisible(true);
insets=getInsets();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public static void main(String[] args){
new TraceMouse();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询