在panel上用滑鼠拖曳button

本文介绍了一个使用Java Swing实现按钮拖动功能的例子。通过监听鼠标事件,实现了按钮在窗口内的自由移动,并确保按钮不会移出窗口边界。此示例展示了如何利用MouseListener和MouseMotionListener来响应用户的鼠标操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import javax.swing.*;
import java.awt.*;

import java.awt.event.*;
import java.awt.image.ImageObserver;
import java.util.Vector;
import java.net.URL;

public class ButtonMove extends JFrame {

JButton jButton1 = new JButton();
int focusx = 0;
int focusy = 0;

public ButtonMove() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}

private void jbInit() throws Exception {
jButton1.setBounds(new Rectangle(86, 113, 73, 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();


}
}

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;
}

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

public static void main(String args[]) {
new ButtonMove();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值