我有一個沒有裝飾(沒有標題欄,關閉按鈕等)的JFrame,我可以使用setLocation()和鼠標位置在屏幕上拖動。Java的mouseExited事件觸發frame.setLocation()被調用時
遺憾的是,事件的mouseExited是在窗口的第一個舉動稱爲...
- 移動鼠標到窗口的mouseEntered事件被觸發
- 點擊鼠標的mousePressed和事件觸發。
- 拖動鼠標和mouseDragged事件被觸發,並調用setLocation。
- mouseExited事件被觸發,即使鼠標仍在窗口中!
- 此時將鼠標移出窗口不會觸發mouseExited。
- 移動鼠標並重新將重新回到步驟1
我該如何解決這個問題,除了在屏幕上只是手動測試鼠標的位置等?
編輯:下面的代碼
import java.awt.*;
import javax.swing.*;
import java.awt.Event;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
class DragNDropper implements MouseMotionListener, MouseListener
{
private int x, y;
private int dx, dy;
private boolean clicked;
private JFrame frame;
public DragNDropper(JFrame frame)
{
dx = dy = 0;
this.frame = frame;
}
public void mouseDragged(MouseEvent e)
{
x = e.getXOnScreen();
y = e.getYOnScreen();
frame.setLocation(x-dx, y-dy);
}
public void mouseMoved(MouseEvent e)
{
x = e.getXOnScreen();
y = e.getYOnScreen();
}
public void mouseClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
clicked = true;
dx = e.getX();
dy = e.getY();
}
public void mouseReleased(MouseEvent e)
{
clicked = false;
}
public void mouseEntered(MouseEvent e)
{
System.out.println("Mouse entered");
}
public void mouseExited(MouseEvent e)
{
System.out.println("Mouse exited");
}
}
public class Program
{
public static void main(String[] argv)
{
JFrame jf = new JFrame();
DragNDropper dnd = new DragNDropper(jf);
jf.setSize(new Dimension(512, 512));
jf.addMouseListener(dnd);
jf.addMouseMotionListener(dnd);
jf.show();
}
}
爲了更好的幫助,請發佈[MCVE](http://stackoverflow.com/help/mcve)來顯示問題。 –
@AndrewThompson完成。 –
錯誤:在類DragNDropper中找不到主要方法,請定義主要方法爲: public static void main(String [] args)'..一個MCVE包含一個main。 –