繁体   English   中英

尝试移动未对齐的JFrame时出现抖动

[英]Jittering when trying to move undercorated JFrame

我制作了一个未修饰的名为mainWindow JFrame 我在其顶部添加了一个名为dragBarJLabel ,并为其提供了所需的尺寸(如下所示)。 当我单击标签时,使用两个侦听器使窗口根据鼠标移动。 一个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);
     }
}

但是,在您的情况下,您不想拖动标签,而是拖动窗口,则需要将事件转发到窗口。

请查看“ 移动窗口”以获取上述代码的更复杂的实现,该代码还添加了其他功能,可以轻松地移动窗口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM