How to make a button with relative position using G4P

edited November 2017 in Library Questions

As the title mentions, i need to change the position of a button when the size (width and height) changes. is this posible?

Answers

  • Answer ✓

    I assume you mean when the window size changes rather than the button size ;)

    Although G4P does not have direct support for relative positioning of controls it is easy to do this in the sketch code.

    This sketch demonstrates 2 buttons attached to the bottom-centre and right-middle positions in the window.

    /**
     This sketch demonstrates how to make the position of G4P controls
     relative to the window size.
    
     It creates two buttons attached to the bottom edge centre and right
     edge middle. As the window is resized the buttons remain in the same 
     relative position irrespective of the window sie.
    
     All the work is done in the pre() method which is always executed immediately 
     before the draw() method. Basically it keeps track of the current window size 
     and repositions the controls when it changes.
    
     created by Peter Lager 2017
     */
    
    import g4p_controls.*;
    
    GButton btn0, btn1;
    int pWidth, pHeight;
    
    void setup() {
      size(600, 400);
      // This will force the control to be repositioned in the pre() method
      pWidth = 0;
      pHeight = 0;
      // There is no need to specify the button positions as they will be 
      // recalulated in the pre() method
      btn0 = new GButton(this, 0, 0, 100, 20, "Bottom Centre");
      btn1 = new GButton(this, 0, 0, 100, 20, "Right middle");
      registerMethod("pre", this);
      surface.setResizable(true);
    }
    
    void pre() {
      if (pWidth != width || pHeight != height) {
        float nx, ny; // used to calculate new control positions
        // Window has been resized so
        // Move btn0 to bottom centre
        nx = (width - btn0.getWidth()) / 2;
        ny = height - btn0.getHeight() - 2;
        btn0.moveTo(nx, ny);
        // Move btn1 to right middle
        nx = width - btn1.getWidth() - 2;
        ny = (height - btn1.getHeight())/2;
        btn1.moveTo(nx, ny);
        // save current widow size
        pWidth = width;
        pHeight = height;
      }
    }
    
    void draw() {
      background(240);
    }
    
  • Yes, i mean that. thanks a lot!!

Sign In or Register to comment.