Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Positioning dialogs on screen...  RSS feed

 
Igor Romanov
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometimes you need to display a dialog window on screen, so that it will be center-aligned on parent's window. But how to do this if you have no reference to parent window, for example when overriding actionPerformed() method. Now I doing it like that:
if( e.getSource() instanceof Component )
{
Component comp = (Component) e.getSource();
Frame[] frms = Frame.getFrames();
for( int i=0; i<frms.length; i++ )
{
if( frms[i].isAncestorOf( comp ) )
{
af = frms[i];
break;
}
}
}
Is it ok, or there's a better way?
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've always used -
 
Igor Romanov
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for a hint!
 
Igor Romanov
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems, that this will not help if JMenuItem is a source object...
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason it doesn't work is because the getWindowAncestor() method just does a getParent() until it hits a Window or null. The problem is, for MenuItems, a JPopupMenu interrupts the getParent() hierarchy, so getWindowAncestor() hits null. There should probably be either a test for JPopupMenu in the getWindowAncestor() code somewhere to fix this, but you can also use this workaround -
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!