簡體   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