鼠标事件移动框架不起作用

时间:2015-09-03 01:41:08

标签: java swing mouseevent mouse

我有以下代码:

panel.addMouseListener(new MouseAdapter() {
    public void mouseDragged(MouseEvent e) {
        frame.setLocation(e.getXOnScreen(), e.getYOnScreen());
    }
});

panelJPanel,并且已包含所有导入。现在,当我拖动panel时,frame不会移动一点点。为什么会这样,我该如何解决呢?

编辑 frame未修饰。
编辑 mouseDragged未被触发 - 这是需要解决的问题! 编辑 :代码!!!!!

package user_interface;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame {
    public Test() {
        this.setUndecorated(true);
        this.setLayout(new GridLayout(3, 3, 3, 3));
        for (int i = 0; i < 4; i++) {
            this.add(new JPanel());
        }
        JPanel panel = new JPanel();
        panel.setBackground(new Color(0));
        panel.setToolTipText("Drag to move frame");
        this.addMouseListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e) {
                Test.this.setLocation(e.getXOnScreen(), e.getYOnScreen());
                System.out.println(e);
            }
        });
        this.add(panel);
        for (int i = 0; i < 4; i++) {
            this.add(new JPanel());
        }
    }

    public static void main(String... args) {
        Test test = new Test();
        test.setSize(750, 500);
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 3
        test.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:1)

为此目的添加MouseMotionListener。

JPanel panel = new JPanel();
panel.setBackground(new Color(0));
panel.setToolTipText("Drag to move frame");

panel.addMouseMotionListener(new MouseMotionAdapter() {
    public void mouseDragged(MouseEvent e) {
       super.mouseDragged(e);
       Test.this.setLocation(e.getXOnScreen(), e.getYOnScreen());
       System.out.println(e);
    }
});

this.setContentPane(panel);