javaswingjframewindowlistener

JFrame drag listener?


I am looking for some sort of WindowMotionListener or something of that sort, so when I drag a window by the title bar (or otherwise) I can get location information the same way I would with a MouseMotionListener. I'm trying to make a Swing component that works sort of like MFC does, where you can drag a window into a location and have it snap into it (example: https://i.sstatic.net/9vKRR.jpg).

So far, I've gotten the snapping down and the dragging when the user drags the frame by it's contents, but not by title bar which would be much easier for the end user. Is there any way to do get a sort of window drag event? Would I have to make my own windows decorations and add a "drag" even to them?

Any help would be greatly appreciated


Solution

  • I want to get events when the window is moved. ... my main issue is that there is no way to determine if a user is dragging a jframe around

    Well, what about a ComponentListener on the JFrame?...

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