Java

Java JFrame怎样实现拖拽功能

小樊
81
2024-11-19 17:20:51
栏目: 编程语言

在Java中,要实现JFrame的拖拽功能,你需要使用MouseListener和MouseMotionListener。以下是一个简单的示例,展示了如何实现这个功能:

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

public class DraggableJFrame extends JFrame {

    private Point dragCursorPoint;
    private Point dragFramePoint;

    public DraggableJFrame() {
        setTitle("Draggable JFrame");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                dragCursorPoint = e.getLocationOnScreen();
                dragFramePoint = getLocationOnScreen();
            }
        });

        addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                Point newCursorPoint = e.getLocationOnScreen();
                Point newFramePoint = new Point(
                        newCursorPoint.x - dragCursorPoint.x + dragFramePoint.x,
                        newCursorPoint.y - dragCursorPoint.y + dragFramePoint.y);
                setLocation(newFramePoint);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            DraggableJFrame frame = new DraggableJFrame();
            frame.setVisible(true);
        });
    }
}

这个示例中,我们创建了一个名为DraggableJFrame的类,它继承自JFrame。我们重写了mousePressed和mouseDragged方法,分别用于记录鼠标按下时的屏幕坐标和拖拽时的屏幕坐标。在mouseDragged方法中,我们计算了新的JFrame位置,并将其设置为当前位置。这样,当你拖动鼠标时,JFrame也会跟随鼠标移动。

0
看了该问题的人还看了