Sunday, February 1, 2009

Monday Feb 2, part three: an applet gui with a button that does something!

OK, so now maybe you're thinking: "this is cool, but how can I make my button DO something?" Well I'm glad you asked, because this is how you do it, and it all has to do with a little item called an "action listener":



A) first, you have to add another import statement at the very top of your program; it looks like this:

import java.awt.event.*; // so you can make stuff happen



B) right after the public class declaration, where you see "extends Applet", you have to add this statement:

implements ActionListener

this allows your program to make use of the event library



C) to make your button able to performk an action, you have to give it access to an actionlistener. Without it, its kind of like having your cellphone on silent: you never hear it ring!

b.addActionListener(this);



D) Finally, you have to add an actionPerformed method. This is what dictates what happens when you click on that button:

public void actionPerformed(ActionEvent e)
{
setBackground(Color.black);
}




As you may have guessed, this button should now be able to make the background of the applet turn black. Don't worry, we will be upgrading this button's capabilities pretty soon!



cheers,

Uncle Paulie

No comments:

Post a Comment