首页 > 解决方案 > JFrame拖动监听器?

问题描述

我正在寻找某种 WindowMotionListener 或类似的东西,所以当我通过标题栏(或其他方式)拖动窗口时,我可以像使用 MouseMotionListener 一样获取位置信息。我正在尝试制作一个类似于 MFC 的 Swing 组件,您可以在其中将一个窗口拖到一个位置并让它卡入其中(例如:https ://imgur.com/LWSXv9x )。

到目前为止,当用户通过其内容拖动框架时,我已经完成了捕捉和拖动,但不是通过标题栏,这对最终用户来说会容易得多。有没有办法获得某种窗口拖动事件?我是否必须制作自己的窗户装饰并为它们添加“拖动”?

任何帮助将不胜感激

标签: javaswingjframewindowlistener

解决方案


我想在窗口移动时获取事件。...我的主要问题是无法确定用户是否正在拖动 jframe

那么,关于...ComponentListenerJFrame呢?

import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Main {
    
    private static void createAndShowGUI() {
        final JFrame frame = new JFrame("Drag frame");
        
        frame.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentMoved(final ComponentEvent e) {
                System.out.println("New frame location: " + frame.getLocation());
            }

            @Override
            public void componentResized(final ComponentEvent e) {
                System.out.println("New frame size: " + frame.getSize());
            }
        });
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JLabel("Drag the title bar and see the logs..."));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(Main::createAndShowGUI);
    }
}

推荐阅读