Thursday, February 19, 2009

Mon Feb 23: Panels and layouts, part one

OK, to begin with, lets set up a new program that is very basic: one frame, one button, and the button can only make the program close. I have treeware handouts; aditionally, you can download this "startup" program at this address:

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

there's only one file in this folder and its called "FebPanel.java". Download it to your Java folder now, then save it, compile it and run it, just to make sure we got the easy stuff done.

You ready? OK, let's go then:

the first thing you will want to do is declare your Panel, like so:
Panel myFirstPanel;

I would put that line right below where you declared your Button

just below that, you will declare six TextFields, like so:
TextField one, two, three, four, five, six;

OK, now its time to actually create your Panel, add one TextField to it, and then ADD THE PANEL TO THE FRAME. Here's how it gets done:

A) just below this line:
onePanel.add(exit);

add this block of code:
myFirstPanel = new Panel(); //create the panel
//set a background color for the Panel
myFirstPanel.setBackground(Color.yellow);
//set different layout for Panel
myFirstPanel.setLayout(new GridLayout(2,3));

This creates a new Panel and gives it a yellow back color. MOST IMPORTANTLY, it gives this Panel a different layout than the rest of your frame. A grid layout lines stuff up using a well, a GRID. In this case, you will eventually end up with two rows of three TextFields each.

B) For now, lets just add one TextField, right below the code block you just added:

one = new TextField("hello"); //make a new textField
myFirstPanel.add(one); //add that TextField to Panel

C) Finally , add the Panel to the Frame by adding this line:
onePanel.add(myFirstPanel); //add panel to frame

just above this line:
onePanel.show();

OK, re-compile, then run the program, and see what you get!

No comments:

Post a Comment