我倾向于通过创建静态引用然后鼠标事件来更新JFrame
位置,从而使我的底涂Point
非常笨拙。
所以为了更好地理解Threads,我想移动一个非常简单的底涂JFrame
,如下所示:
JFrame
MouseListener
Point p = Mousevent.getPoint();
Point p = Mousevent.getPoint();
同时让线程不断更新JFrame
的位置。
但是我无法弄清楚为什么controllerThread,不会做多次迭代?还要非常感谢下面代码可怕的原因。
public AnimationStation() throws HeadlessException {
P=this.getLocation();
run();
class ControllerThread extends Thread{
JFrame j;
public ControllerThread(JFrame j){
this.j = j;
}
@Override
public void run(){
this.j.setLocation(P);
}
}
ControllerThread ct = new ControllerThread(this);
ct.run();
//ct.start();
}
@Override
public void run() {
this.setSize(d);
Container cp = this.getContentPane();
P=this.getLocation();
this.setUndecorated(true);
this.setVisible(true);
this.setAlwaysOnTop(true);
this.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent me) {
P = me.getPoint();
}
@Override
public void mousePressed(MouseEvent me) {
P = me.getPoint();
}
@Override
public void mouseReleased(MouseEvent me) {
P = me.getPoint();
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
});
}
答案 0 :(得分:3)
首先,您的ControllerThread
不会在其他线程中运行,因为您只需调用其run()
方法。要启动新线程,您必须调用其start()
方法。
其次,如果要在移动鼠标时连续移动框架,则必须注册MouseMotionListener
,MouseListener
仅捕获鼠标按下和释放的事件(而不是鼠标移动或拖动事件)。
建议的解决方案:
注册MouseListener
以检测何时开始拖动(mousePressed()
)和MouseMotionListener
以检测拖动框架的数量(mouseDragged()
),并移动框架拖动的距离:
public AnimationStation() {
MouseAdapter ma = new MouseAdapter() {
int lastX, lastY;
@Override
public void mousePressed(MouseEvent e) {
lastX = e.getXOnScreen();
lastY = e.getYOnScreen();
}
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
// Move frame by the mouse delta
setLocation(getLocationOnScreen().x + x - lastX,
getLocationOnScreen().y + y - lastY);
lastX = x;
lastY = y;
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}