当窗口未装饰时,是否有可能通过点击窗口中的其中一个面板来移动窗口?
我有一个主要的面板,无边框40像素的大小,几个面板与控件里面,我想移动窗口,当点击该边框.那可能吗?
解决方法
您可以使用边框将另一个面板放在面板上,使边框可见.使用以下代码移动窗口.
public class MotionPanel extends JPanel{ private Point initialClick; private JFrame parent; public MotionPanel(final JFrame parent){ this.parent = parent; addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { initialClick = e.getPoint(); getComponentAt(initialClick); } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { // get location of Window int thisX = parent.getLocation().x; int thisY = parent.getLocation().y; // Determine how much the mouse moved since the initial click int xMoved = (thisX + e.getX()) - (thisX + initialClick.x); int yMoved = (thisY + e.getY()) - (thisY + initialClick.y); // Move window to this position int X = thisX + xMoved; int Y = thisY + yMoved; parent.setLocation(X,Y); } }); } }
我一直在使用这段代码一段时间,为未装饰的窗口创建一个自定义标题栏.P.S.:您可以通过扩展JComponent而不是JPanel来推广此示例.