Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Dragging a borderless frame in Java

4.00/5 (1 vote)
13 Nov 2011CPOL1 min read 30K  
A borderless JFrame needs an extra bit of coding to make it draggable
In case of giving your application a fancy look, sometimes you may consider it to have some custom border.You will remove the default border from it & wish to have it the draggable capability (as you know, the border is the one that enables your JFrame to move when you drag).So how to achieve this?
It's simple. Let's say your application's main window(the JFrame that will be visible at first launch) is MyWindow such that:
Java
class MyWindow extends JFrame


And you make it borderless by:

Java
this.setUndecorated(true);


Now let's say you have made your custom window using your own GUI coding,images & bla,bla. What you need now is to drag it when you wish. Create fields like the following:
Java
int posX=0,posY=0;


Now we do the following coding:

Java
this.addMouseListener(new MouseAdapter()
{
   public void mousePressed(MouseEvent e)
   {
      posX=e.getX();
      posY=e.getY();
   }
});

At last, the main part of it:

Java
this.addMouseMotionListener(new MouseAdapter()
{
     public void mouseDragged(MouseEvent evt)
     {
		//sets frame position when mouse dragged			
		setLocation (evt.getXOnScreen()-posX,evt.getYOnScreen()-posY);
					
     }
})


You are done! Try with a simple JFrame application and you will see your borderless JFrame is moving smoothly as any other business app!
Here[^] is a handy library(by me ;)) for doing these except using extra codes; simple & strong.You can try it too.
Well, I think you have understood the simple coding & the explanation behind it (why did I do each line of coding). In case you want to know a bit more details, don't forget to give me a knock!
Cheers :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)