javaswingcomponentsresizable

Resize java swing component from UI


I need to make resizable java swing component (JPanel), so when I click on the border of that component and drag with cursor to somewhere else, the component will change size by mouse position. Has this any easy solution?


Solution

  • Attach a MouseListener to the component, record mouse position at start of dragging in mouse pressed method after checking whether the mouse is pressed on what you have defined as border, then resize the component in mouse released method calculating the size difference by subtracting mouse positions at start and end of dragging.

    If you need / want continuous resizing while you drag, use a MouseInputListener instead, record the size of the component too in the mouse pressed method and do the resizing in the mouse moved method.

    If you also want to have a visible border, you can maybe add that border to the component and add the mouse listener to the border, so that you know you are on the border when you get the pressed event.