使用鼠标事件和线程移动未修饰的JFrame进行更新

时间:2014-07-25 08:59:18

标签: java swing jframe inner-classes

我倾向于通过创建静态引用然后鼠标事件来更新JFrame位置,从而使我的底涂Point非常笨拙。

所以为了更好地理解Threads,我想移动一个非常简单的底涂JFrame,如下所示:

  • 创建JFrame
  • 添加MouseListener
  • onMousePressed:Point p = Mousevent.getPoint();
  • onMouseReleased: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) {

        }
    });


}

1 个答案:

答案 0 :(得分:3)

首先,您的ControllerThread不会在其他线程中运行,因为您只需调用其run()方法。要启动新线程,您必须调用其start()方法。

其次,如果要在移动鼠标时连续移动框架,则必须注册MouseMotionListenerMouseListener仅捕获鼠标按下和释放的事件(而不是鼠标移动或拖动事件)。

建议的解决方案:

注册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);
}