Tuesday, February 24, 2009

March 5: Menus, part one

Greetings, JavaNoidz: today, we will be adding menus to your programs. As always, your ever so helpful instructor and all around good guy has set up the base level of the program for you; it can be found here:


http://www.box.net/shared/p2gx5ecl5b

the file is named JavaMenus. Please download it and compile it and make sure it runs. Got it? K3WLLLLLLL!!!!! Let's go!


A) first, let's understand some concepts. A "MenuBar" is just that: a bar that contains menus. It's like the different toolbars you can have in IE or Firefox, and they can hold many


"Menus". Menus have some sort of text label, such as FILE, EDIT, VIEW, so on and so forth. When you click on a Menu, you get to see a big list of


"MenuItems". Under FILE, you might see MenuItems such as NEW, OPEN, SAVE, PRINT, EXIT


B) OK, so let's start by declaring one MenuBar, one Menu and several MenuItems, like so:

MenuBar myHouse;
Menu myRoom;
MenuItem inky,pinky,blue,quit;



do so just below the line that declares your exit button:
Button exit; //declare button


C) Next, let's get into your constructor and actually create a menubar and a menu:
myHouse = new MenuBar(); //create a MenuBar
myRoom = new Menu("FILE"); //create a Menu



do this right below where I added the "exit" button to the frame
Gumby.add(exit);


D) Just below where you created the menubar and menu, you will create one menuitem, give it an actionListener, then add it to the menu, like so:
quit = new MenuItem("End the program"); //create a menu item
quit.addActionListener(this);//give it a listener
myRoom.add(quit); //add this menuitem to the menu



E) Just below that, add these two lines to add the menu to the menubar, and the menubar to the frame:
myHouse.add(myRoom);//add the menu to the menubar
Gumby.setMenuBar(myHouse);//add the menubar to the frame



F) At this point, run the program to make sure you can see the menubar, its one menu and that menu's only menuitem. When you click on "End the program" notice that it doesn't do that. I now give you some time to figure out how to make that happen. Hint: all the code you need is sitting right in front of you.


cheers,
Uncle Paulie

No comments:

Post a Comment