Get notified when the user finishes resizing a JFr

2019-07-26 16:09发布

I have a fractal generation component (a subclass of JPanel) inside a JFrame. When the user resizes the window, it takes quite a while to update the fractal to the new size.

I currently have a ComponentListener on the JPanel, but its componentResized event is called every time the user moves the mouse while dragging the window border. This means that the fractal is told to resize many times, and slowly (over the course of a few minutes) grows to the new size.

Is there a way to be notified when the user releases the mouse button, so that I can only change the fractal size when the user has finished resizing?

Others have reported this happening when the listener is attached to the JFrame instead, but this doesn't work for me (and others), for some reason.

3条回答
smile是对你的礼貌
2楼-- · 2019-07-26 16:43

Instead of starting the calculation each time you receive a receive-event, you can only start the calculation after you received the last event by using a timer, e.g. in pseudo-code (or at least code which I typed here directly and not in my IDE)

private Timer recalculateTimer = new Timer( 20, myRecalculateActionListener );

constructor(){
  recalculateTimer.setRepeats( false );
}
@Override
public void componentResized(ComponentEvent e){
  if ( recalculateTimer.isRunning() ){
    recalculateTimer.restart();
  } else {
    recalculateTimer.start();
  }
}

And you can still combine this with Andrews suggestion to use an image which you stretch until the calculation has actually finished.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-26 16:46
  • you have look at HierarchyListener, where you can listening for HierarchyEvent with interface to HierarchyBoundsListener

  • basically nothing wrong with ComponentListener, but you have to wrapping expected events to the Swing Timer, in the case that events repeated, only to call Timer#restart(), output from Swing Timer should be Swing Action

查看更多
Luminary・发光体
4楼-- · 2019-07-26 16:52

It's a bit late, but it looks like no one found the correct answer. I found that when you call child.updateUI() inside a ComponentListener (componentResized block) of a window, this child resizes it self and updates its content. Using timers is unsafe.

查看更多
登录 后发表回答