Programmatically Adding Controls

  • Hello,

    I am working on my first OS X desktop app, but have been developing for years.

    I would like to add and control my NSButtons programmatically to the
    NSWindow in my .nib file. I don't see how to add them to the nib's
    window however.

    I'm expecting something like this in my Java class:
    NSWindow myWindow; //this is set up as an outlet in the nib, but has
    no buttons on it
    NSButton myButton = new NSButton();
    myButton.x_Y_Coords(110,120); // where it should appear in the window
    myButton.onClick("someMethod"); //Called when you click it

    Voila! The new button appears in the window and when I click it,
    someMethod() is called.

    I know syntactically I'm way off, but this is what I'd like to
    accomplish. I've spent hours pouring through documentation regarding
    NSView, NSControl, NSCell, NSBox, as well as Jesse Feiler's Mac OS X
    Developer's Guide, but I cannot see how to set up the controls on my
    window programmatically.

    The reason I need to do this is because I need to dynamically place
    and remove buttons as well as change a buttons bindings (for what
    method it calls) depending on what the user clicks on.

    Is this possible? Any help is greatly appreciated. (Especially a down
    and dirty sample app that simply does the above)


  • - (void)addButtonAtPoint:(NSPoint)somePoint toWindow:(NSWindow *)someWindow
    // add a 100 by 50 button the content view of someWindow at somePoint.  Set
    the action of the
    // button to anAction.  The target will remain nil so the action will be
    sent up the responder chain.
      NSButton    *testButton =  [[NSButton alloc]
    initWithFrame:NSMakeRect(somePoint .x, somePoint.y,100,50)];

      [testButton setAction:anAction];
      [[someWindow contentView] addSubview:testButton ];
      [testButton  release];
previous month july 2002 next month
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        
Go to today