Search code examples
javatitlebar

Moving and resizing shell with mouse (custom titlebar)


I want to create custom titlebar so I have to write code that will allow user to resize and move shell (I am using SWT), but I have got problem with

a) capturing mouse up

b) resizing

    shell.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseDown(final MouseEvent arg0) {
            move=true;
            oldx=arg0.x;
            oldy=arg0.y;
            Display.getDefault().syncExec(new Runnable() {
                @Override
                public void run() {
                    while (move) {
                            shell.setLocation(MouseInfo.getPointerInfo().getLocation().x-oldx, MouseInfo.getPointerInfo().getLocation().y-oldy);
                    }
                }

            });
        }
        @Override
        public void mouseUp(MouseEvent arg0) {
            move=false;
        }
    });

Moving shell is working but it doesn't capture mouse up event. Also I don't know how to make resizing. I have tried

shell.setSize(MouseInfo.getPointerInfo().getLocation().x-shell.getBounds().x, MouseInfo.getPointerInfo().getLocation().y-shell.getBounds().y);

but it doesn't work.


Solution

  • Your problem is that you are expecting event #2 (mouseDown) to fire, before event #1 (mouseUp) has finished firing. SWT processes events one at a time. You need #2 to fire to finish operations in #1, which will never happen because #2 will not run. This is a deadlock situation. You would need to move the window as the mouse moves, not based on the mouseDown event. Take a look a this example.