Using the Online Documentation by Example
So how would you use a button in an
application? Well, just as we did for our Announcer class, we
would simply use the "new" keyword to instantiate a Button and then
use dot notation to affect its state. For example:
Button myButton = new Button();
myButton.setLabel("My Button");
Let's consider a more complex example
in which we place a button inside a frame. We will use the constructor
to display "Hello Cyberspace" and we will color it white on black.
using methods inherited from Component. Don't get to hung up
on the complexities of layout, just get the basic idea! However,
do note the first line. It is essential that you import the
awt package so that java will know where it can find the Button
class. Notice also that we use the dot notation to reference
the fields black and white in the Color class.
Actually, you could bypass the import statement
by referring to the absolute path of Button such as
java.awt.Button myButton = new java.awt.Buttton();
However, the import statement will save you a lot of typing
since it creates a shortcut for you.
import java.awt.*;
public class TestFrame
{
public static void main(String[] args)
{
Frame f = new Frame();
f.reshape(10,10,200,200);
Button b = new Button("Hello Cyberspace");
b.setBackground(Color.black);
b.setForeground(Color.white);
f.add(b);
f.show();
}
}
Selena Sol contributes to the JavaBoutique's Introduction to Java. Selena currently works for Barclays Capital in London, one of the leading global investment banks in Europe and has worked as a software developer for the National Center for Human Genome research, Microline Software, Neuron Data, and Electric Eye in Singapore. Selena is perhaps best-known for creating the Public Domain Web Script Archive (Extropia) and writing several books on Web Programming (Perl, CGI, Java).
Email: selena@extropia.com
|