4

i m creating a JFrame with four buttons in its titleBar.

JFrame frame=new JFrame("custom JFrame with 4 buttons in title");
frame.setUndecorated(true);

JPanel button_panel=new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton button_1=new JButton("+");
JButton button_2=new JButton("↑");
JButton button_3=new JButton("-");
JButton button_4=new JButton("system tray");

button_panel.add(button_1);
button_panel.add(button_2);
button_panel.add(button_3);
button_panel.add(button_4);

frame.getContentPane().add(button_panel,BorderLayout.NORTH);

now, i have a JFrame with four buttons in its titlebar.

but, how to give drag functionality to this custom JFrame?

Lokesh Kumar
  • 682
  • 2
  • 8
  • 27
  • How do you want the JFrame to be moved? Something like clicking anything in the fame, and then dragging the mouse? – user489041 Mar 31 '11 at 20:02
  • no.. only the top button_panel for dragging purpose – Lokesh Kumar Mar 31 '11 at 20:05
  • Possible duplicate of [Making a java swing frame movable and setUndecorated](https://stackoverflow.com/questions/16046824/making-a-java-swing-frame-movable-and-setundecorated) –  Jun 23 '19 at 09:52

5 Answers5

5

is it the only solution?

Well, the only solution that I know of is to use MouseListeners.

For a more general solution you can check out Moving Windows which allows you to make any Swing component dragable.

camickr
  • 321,443
  • 19
  • 166
  • 288
2

Are you using Mac OS X? A Mac-specific solution is this:

frame.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", true);
Steve McLeod
  • 51,737
  • 47
  • 128
  • 184
1

If you don't care about the offset between mouse position and components location on screen (components upper left corner), this is the easiest solution:

private class DragListener extends MouseAdapter {

   @Override
    public void mouseDragged(MouseEvent e) {
        setLocation(MouseInfo.getPointerInfo().getLocation());
    }
}
Stefan
  • 12,108
  • 5
  • 47
  • 66
1

You can drag a JFrame by it's contents by setting up the MouseListener appropriately. This post has an example.

Bala R
  • 107,317
  • 23
  • 199
  • 210
0

You can simply override mousepressed and mousedragged methods as shown:

private int tx, ty;
private void titlebar_mousePressed(MouseEvent m)
{
    tx= m.getX();
    ty=m.getY();
}
private void titlebar_mouseDragged(MouseEvent m)
{
    titlebar.setLocation(m.getXOnScreen() -tx, m.getYOnScreen() -ty);
}
Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38