I was playing with writing a quick time tracking application called Efficiency which needed to be always ontop of other windows and therefore be a subtle as possible. I therefore decided to undecorate the window, however the user is then unable to reposition the window, so I wrote a some code to quickly allow them to do this by just dragging the JFrame.
My class extends the javax.swing.JFrame class, so I’ve set a few properties in the initComponents() function and more importantly added listeners for MousePressed and MouseDragged.
private void initComponents() {
...
setAlwaysOnTop(true);
setBackground(new java.awt.Color(0, 0, 0));
setResizable(false);
setUndecorated(true);
addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
formMousePressed(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
formMouseDragged(evt);
}
});
...
}
Firing an action on mousePressed is required to get the original location of the window. This fires the following function, setting the two variables which are of type java.awt.Point:
private void formMousePressed(java.awt.event.MouseEvent evt) {
this.start_drag = this.getScreenLocation(evt);
this.start_loc = this.getLocation();
}
The mouse dragged function is as follows:
private void formMouseDragged(java.awt.event.MouseEvent evt) {
Point current = this.getScreenLocation(evt);
Point offset = new Point((int) current.getX() - (int) start_drag.getX(),
(int) current.getY() - (int) start_drag.getY());
Point new_location = new Point(
(int) (this.start_loc.getX() + offset.getX()), (int) (this.start_loc
.getY() + offset.getY()));
this.setLocation(new_location);
}
You’ll also need the utilty funciton to convert the points to a screen location:
Point getScreenLocation(MouseEvent e) {
Point cursor = e.getPoint();
Point target_location = this.getLocationOnScreen();
return new Point((int) (target_location.getX() + cursor.getX()),
(int) (target_location.getY() + cursor.getY()));
}
Reference
- Drag and Move – material from java2s.com used as a basis but using an external MoveMouseListner class
Photo Credit: dongga BS