java中如何判断鼠标拖拽时的方向

现在有一个Button,鼠标点着按钮拖拽时要判断是往哪个方向拖的,这要怎么写?... 现在有一个Button,鼠标点着按钮拖拽时要判断是往哪个方向拖的,这要怎么写? 展开
 我来答
匿名用户
推荐于2016-03-05
展开全部
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonMove extends JFrame {

JButton jButton1 = new JButton();
JLabel lb = new JLabel();
int focusx = 0;
int focusy = 0;
int xa=0,ya=0;
public ButtonMove() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}

private void jbInit() throws Exception {
jButton1.setBounds(new Rectangle(86, 113, 73, 25));
this.add(lb);
lb.setBounds(new Rectangle(20, 360, 400, 25));
jButton1.setText("jButton1");
jButton1.addMouseListener(new MouseProcess() {
});
jButton1.addMouseMotionListener(new MouseMotionProcess());

this.setLocale(java.util.Locale.getDefault());
this.getContentPane().setLayout(null);
this.getContentPane().add(jButton1, null);
this.setSize(400, 500);
this.setVisible(true);
}

private class MouseProcess extends MouseAdapter {

public void mouseClicked(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
focusx = e.getX();
focusy = e.getY();
xa=focusx;
ya=focusy;
}
public void mouseReleased(MouseEvent me){

}
}

private class MouseMotionProcess extends MouseMotionAdapter {

public void mouseDragged(MouseEvent e) {
Container container = jButton1.getParent();
int w = container.getWidth();
int h = container.getHeight();

int x = jButton1.getX() + e.getX() - focusx;
int y = jButton1.getY() + e.getY() - focusy; if (x + jButton1.getWidth() > w) {
x = w - jButton1.getWidth();
}
if (y + jButton1.getHeight() > h) {
y = h - jButton1.getHeight();
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if(e.getX()-xa>0){
if(e.getY()-ya>0){
lb.setText("方向---〉右下");
}
else if(e.getY()-ya<0){
lb.setText("方向---〉右上");
}
else{
lb.setText("方向---〉右");
}
}
else if(e.getX()-xa<0){
if(e.getY()-ya>0){
lb.setText("方向---〉左下");
}
else if(e.getY()-ya<0){
lb.setText("方向---〉左上");
}
else{
lb.setText("方向---〉左");
}
}
else{
if(e.getY()-ya>0){
lb.setText("方向---〉下");
}
else if(e.getY()-ya<0){
lb.setText("方向---〉上");
}
}
xa = e.getX();
ya = e.getY();

jButton1.setLocation(x, y);
//jButton1.setLocation(x, y + jButton1.getHeight());
container.repaint();
container = null;
}
}

public static void main(String args[]) {
new ButtonMove();
}
}
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

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

类别

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

说明

0/200

提交
取消

辅 助

模 式