开发者

how to give drag functionaly to a JFame with no titleBar?

开发者 https://www.devze.com 2023-02-20 22:52 出处:网络
i m creating a JFrame with four buttons in its titleBar. JFrame frame=new JFrame(\"custom JFrame with 4 buttons in title\");

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?


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.


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

frame.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", true);


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


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());
    }
}


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消