温馨提示×

如何用java拖拽建立窗体

小亿
85
2024-03-12 16:12:47
栏目: 编程语言

在Java中实现窗体的拖拽功能可以通过以下步骤实现:

  1. 创建一个 JFrame 对象并设置窗体的标题和大小。
  2. 添加一个 MouseListener 和 MouseMotionListener 监听器到窗体中,用于监听鼠标按下和释放、鼠标拖拽等事件。
  3. 在鼠标按下事件中记录鼠标按下时的坐标,并设置一个标志位来表示窗体是否可以拖拽。
  4. 在鼠标释放事件中清除标志位。
  5. 在鼠标拖拽事件中计算鼠标拖拽的偏移量,并更新窗体的位置。

下面是一个简单的示例代码实现窗体的拖拽功能:

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

public class DragWindow extends JFrame {
    private int lastX, lastY;

    public DragWindow() {
        setTitle("Drag Window Example");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                lastX = e.getX();
                lastY = e.getY();
            }
        });

        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                int newX = getLocation().x + e.getX() - lastX;
                int newY = getLocation().y + e.getY() - lastY;
                setLocation(newX, newY);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DragWindow().setVisible(true);
            }
        });
    }
}

运行上面的代码,可以看到一个窗体,并且可以通过拖拽窗体标题栏来移动窗体的位置。

0