Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have "movable"/"draggable" components like JButtons, JTextFields in a JFrame?

Basically I plan to place some buttons, textfields, labels, etc. on a JFrame and I would like to make it possible that a user can move the different components around on that JFrame with the mouse.

I have seen various ways with MouseListeners, subclassed JComponent code, DropSource/DropTarget implementations and so on, but I'm unsure which is the "recommended" way (I don't need to support "drag and drop" between different Frames/Applications which is what most examples seem to do).

like image 822
soc Avatar asked Feb 19 '11 16:02

soc


2 Answers

The Component Mover can do this for you.

like image 143
camickr Avatar answered Nov 03 '22 07:11

camickr


Use the GlassPane: http://download.oracle.com/javase/tutorial/uiswing/components/rootpane.html

It's an invisible panel that sits on top of all other components. You can attach mouse listeners to it and then use SwingUtilities.getDeepestComponentAt() to figure out which component was clicked on beneath the GlassPane. Then use a mouseDragged listener on the glasspane and set the component location based on the mouse dragged event.

You will need to set the layout of your container to "null" so the components' setLocation will work.

like image 44
PlutoTheCat Avatar answered Nov 03 '22 06:11

PlutoTheCat