OK, so now we've made a class that creates a method we can use. Can we do the same for components? For instance, can we create a custom Panel with buttons already on it that we can stick onto any program we want.
You betcha we can!
Here's how we do it:
A) In the same folder as your other two classes, you will create a new class. Let's call it "ButtonPanel"; it'll start off looking like this:
import java.awt.*;
import java.awt.event.*;
class ButtonPanel extends Panel
{
}//end class
B) compile it and make sure its OK, then we'll declare three buttons in between those curly braces:
Button a,b,c;
C) next, we will make a constructor for this class, right below where we declared those buttons:
ButtonPanel()
{
}
D) Inside the curly braces for that constructor, lets give this custom Panel a GridLayout:
setLayout(new GridLayout(1,3));
and then add in those three buttons we declared. Here's how you do the first one:
a = new Button("Button A");
add(a);
E) COMPILE that new ButtonPanel class, an when you get no errors, get back to your main program. Declare a new object based on the Button Panel class by entering this line:
ButtonPanel myNewPanel;
below this line:
int firstNum, secondNum;
F) Finally, create this new object inside your main program by entering these two lines:
myNewPanel = new ButtonPanel();
Valhalla.add(myNewPanel);
above this final line in your constructor:
Valhalla.show();
Compile, then run the program. Does the custom panel with three buttons show up in your program? Hurrah!
"think good thoughts"
Uncle Paulie
Friday, February 20, 2009
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment