java JFrame不移动

b5buobof  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(115)

我希望我的JFrame在禁用装饰的情况下仍能移动。
我在谷歌上搜索了一下后添加了一个mouseListener,但仍然没有帮助。

public static void main(String[] args) {

        try {
            UIManager.setLookAndFeel(new FlatDarkLaf());
        } catch (Exception errorDesign) {
            logError(errorDesign);
        }

        JFrame frame = new JFrame();
        frame.setBounds(1600, 400, 500, 800);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.setUndecorated(true);
        frame.setVisible(true);

        frame.addMouseListener(new MouseAdapter() {
            private Point mouseOffset;

            @Override
            public void mousePressed(MouseEvent e) {
                mouseOffset = e.getPoint();
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                Point newLocation = e.getLocationOnScreen();
                newLocation.translate(-mouseOffset.x, -mouseOffset.y);
                frame.setLocation(newLocation);
            }

        });

    }

有人知道我做错了什么吗

oxalkeyp

oxalkeyp1#

frame.addMouseMotionListener()必须用于跟踪运动事件,例如鼠标拖动。使用此侦听器时,可以重写mouseDragged方法并接收鼠标拖动事件。
有关更多帮助,请参阅Java教程:https://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html

private static Point mouseOffset;

 public static void main(String[] args) {

        try {
            UIManager.setLookAndFeel(new FlatDarkLaf());
        } catch (Exception errorDesign) {
            logError(errorDesign);
        }

        JFrame frame = new JFrame();
        frame.setBounds(1600, 400, 500, 800);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.setUndecorated(true);
        frame.setVisible(true);

        frame.addMouseListener(new MouseAdapter() {
          @Override
          public void mousePressed(MouseEvent e) {
              mouseOffset = e.getPoint();
          }
        });

        frame.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                Point newLocation = e.getLocationOnScreen();
                newLocation.translate(-mouseOffset.x, -mouseOffset.y);
                frame.setLocation(newLocation);
            }
        });

    }

相关问题