Skip to content
Advertisement

How to create moveable JPanel using BorderLayout?

I want to create a GUI with a sliding Menu. The menu is one of three JPanels organized onto a JFrame with BorderLayout. The Menu in question is on the west side. How can I make it so that the menu can hold Textfields, JLabels, images etc. while having the ability to slide in and out?

Advertisement

Answer

This can be done, but it requires either a custom layout or a null layout. In the latter case, you’ll need to manage the child component’s sizes and placement yourself.

Since a Component “traps” the mouse once a button is pressed, and all mouse events get sent to that same Component until the mouse is released, you only need to listen for mouse drag events on the one Component that serves as the drag handle.

The slidable area, which I’ll call a drawer, can be in the center of a BorderLayout, with the drag handle in the east (or LINE_END) position.

JavaScript

I chose to draw a pattern in the drag handle based on the “drag texture” described in the old Java Look and Feel Design Guidelines. You can of course use whatever appearance you want, including images.

Here is an example use of the class:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement