Search code examples
javagriffonswingbuilder

Swingbuilder - application location centering


I am creating an application using Griffon->SwingBuilder. I would like to able to center the application on the desktop.

I know we have the 'location: [x,y]' argument we can provide on application creation. Is there anyway to access desktop properties to calculate the center?


Solution

  • For various reasons you cannot do it inline. Here is one way to center

    import java.awt.*
    import groovy.swing.*
    
    sb = new SwingBuilder()
    sb.build {
      f = frame(pack:true) {
          label "<html>" + (("This is a very long label."*3) + "<BR>")*5
      }
      Point cp = GraphicsEnvironment.localGraphicsEnvironment.centerPoint
      f.location = new Point((int)(cp.x - f.width), (int) (cp.y - f.height))
      f.show()
    }
    

    The reason you cannot set it in the attributes is that when the attributes are evaluated a child node has not yet been created or stored anywhere. One alternative is to set it as part of the child content block:

      frame(show:true) 
      {
          label "<html>" + (("This is a very long label."*3) + "<BR>")*5
          current.pack()
          Point cp = GraphicsEnvironment.localGraphicsEnvironment.centerPoint
          current.location = new Point((int)(cp.x -current.width/2), (int)(cp.y - current.height/2))
      }
    

    (current is a meta-variable for the containing node).