我有以下代码:
panel.addMouseListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
frame.setLocation(e.getXOnScreen(), e.getYOnScreen());
}
});
panel
是JPanel
,并且已包含所有导入。现在,当我拖动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);
}
}
答案 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);