溫馨提示×

Java JFrame怎樣實(shí)現(xiàn)拖拽功能

小樊
81
2024-11-19 17:20:51
欄目: 編程語言

在Java中,要實(shí)現(xiàn)JFrame的拖拽功能,你需要使用MouseListener和MouseMotionListener。以下是一個簡單的示例,展示了如何實(shí)現(xiàn)這個功能:

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

這個示例中,我們創(chuàng)建了一個名為DraggableJFrame的類,它繼承自JFrame。我們重寫了mousePressed和mouseDragged方法,分別用于記錄鼠標(biāo)按下時的屏幕坐標(biāo)和拖拽時的屏幕坐標(biāo)。在mouseDragged方法中,我們計(jì)算了新的JFrame位置,并將其設(shè)置為當(dāng)前位置。這樣,當(dāng)你拖動鼠標(biāo)時,JFrame也會跟隨鼠標(biāo)移動。

0