【问题标题】:componentResized event for Component in Java, but only execute when mouse releasedJava中Component的componentResized事件,但仅在鼠标释放时执行
【发布时间】:2011-10-07 23:53:14
【问题描述】:

当我的一个组件(一个画布)被调整大小时,我需要进行一些计算。不幸的是,计算可能需要几百毫秒,这会导致调整大小在完成时严重滞后。我想通过仅在调整大小结束时进行计算来解决这个问题(我猜是在释放鼠标按钮时)。我怎样才能做到这一点?到目前为止,我只有以下内容:

MyComponent.addComponentListener(new ComponentAdapter() {
    @Override
    public void componentResized(ComponentEvent e) {
        super.componentResized(e);
        // some calculation
    }       
});

谢谢。

PS:我知道对于 JFrame,resized 事件仅在释放鼠标按钮后才会触发,但不幸的是我无法将我的组件放入 JFrame 或让它扩展 JFrame。

【问题讨论】:

  • 你为什么使用AWT组件?此外,计算是否与正在进行调整大小事件的组件相关?

标签: java events resize components listener


【解决方案1】:

然后您可以延迟启动 javax.swing.Timer 并在调整大小时仅重新启动 Timer 通过调用 Action 或 AbstractAction 你可以计算任何东西并输出到 GUI 将在 EDT 上

【讨论】:

  • +1,计时器是要走的路。 invokeLater() 没有帮助。
  • 使用Timer的时候不需要使用invokeLater()。此外,使用 Timer 的好处是每次生成组件大小调整事件时都继续使用 timer.restart()。将 Thread 与 invokeLater() 结合使用是一种不同的解决方案,需要更多编码,因为您需要支持 restart() 逻辑,并且不应在此回复中建议。它只会混淆海报。如果您认为这是一个很好的解决方案,那么您应该发布单独的回复。
【解决方案2】:

您可以在componentResized() 中设置一个标志并让MouseListener 执行实际工作。

【讨论】:

    【解决方案3】:

    我会像这样做一个 MouseListener:

    public class MouseHandler implements MouseListener
    {
        public void mousePressed(MouseEvent e)
        {
            if(!running)
            {
                thread = new Thread(this);
                thread.start();
                running = true;
            }
        }
    
        public void mouseReleased(MouseEvent e)
        {
            running = false;
            thread = null
        }
    
        public void mouseEntered(MouseEvent e){}
        public void mouseExited(MouseEvent e){}
        public void mouseClicked(MouseEvent e){}
    
        public void run()
        {
            while(running)
            {
                try
                {
                    //repaint the component or move it or somthing.
                    Thread.sleep(1000);
                    // repaint delay
                }catch(Exception e){e.printStackTrace();}
            }
        }
    
        Thread thread;
        boolean running;
    }
    

    如果你想改变组件的位置,你可以加入一个 MouseMotionListener

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-30
      • 2018-10-20
      • 1970-01-01
      • 2018-11-26
      • 2014-10-15
      • 2013-07-05
      • 1970-01-01
      • 2019-11-27
      相关资源
      最近更新 更多