我制作了一个未经装修的mainWindow
JFrame
。我在其顶部添加了一个名为dragBar
的JLabel
,并给了它所需的尺寸(如下所示(。当我单击标签时,我会使用两个侦听器根据鼠标将窗口移动;一个MouseListener
和一个MouseMotionListener
。
问题是,每当我单击标签时,窗口的确会根据鼠标的位置移动,但是它会在屏幕上散布到整个屏幕上,直到我停止移动鼠标或单击按钮。
我的方法错了吗?是什么原因导致了这个问题?这是我的代码:
//what i use to make the dragBar
private JLabel dragBar = new JLabel();
private Point initialClick; //the initial point where I click on the label
//my mainWindow JFrame
private JFrame mainWindow = new JFrame();
private Dimension mainWindowSize = new Dimension(680,410);
//the code I use to set up my mainWindow JFrame
mainWindow.setUndecorated(true);
mainWindow.setShape(new RoundRectangle2D.Double(0, 0, 670, 400, 5, 5));
mainWindow.setSize(mainWindowSize);
mainWindow.setMinimumSize(mainWindowSize);
mainWindow.setResizable(false);
mainWindow.setLocation((screen_size.width/2)- mainWindow.getWidth()/2, (screen_size.height/2)- mainWindow.getHeight()/2);
mainWindow.getContentPane().setBackground(new Color(46, 48, 50, 255));
//the code I use to set up my dragBar label
topContainer.add(dragBar,3); //a Jlayeredpane that contains the dragBar label and is added to the mainWindow
dragBar.setSize(topContainer.getSize());
dragBar.setLocation(0,0);
dragBar.addMouseListener(new MouseListener() {
@Override public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
initialClick = e.getPoint();
}
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
});
dragBar.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
int changeX = e.getX()-initialClick.x;
int changeY = e.getY()-initialClick.y;
mainWindow.setLocation(mainWindow.getX()+changeX, mainWindow.getY()+changeY);
}
@Override public void mouseMoved(MouseEvent e) {}
});
包含dragbar标签的jlayeredpane
不要以为我会使用jlayeredpane。只需在框架的BorderLayout.PAGE_START
中添加一个组件即可。
拖动组件的基本逻辑是:
public class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me)
{
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}
但是,在您的情况下,您不想拖动标签,而是拖动窗口,您的逻辑需要将事件转发到窗口。
查看移动窗口以进行上述代码的更复杂的实现,该代码还添加了其他功能,可以轻松地移动窗口。