(^380) | Event-Driven Input and Output
Add Output to the Content Pane
We have now taken care of all of the steps needed to create a content pane that is ready to
receive information to display. A content pane is called a container classbecause we can add
elements into it. Java supports various specialized container classes in addition to
Container.
Initially, we add only elements called labelsto our panes. A label is a block of
text that is placed into the pane. We add the label to the pane using the addinstance
method. Here is an example:
outputPane.add(new JLabel("This is the text in the label."));
Note that we are instantiating an anonymous object of the class JLabel, within the argument
list. The addmethod places this new object into the pane. We could also declare a variable to
be of class JLabel, assign it a value, and pass the variable as an argument to add:
JLabel newLabel;
newLabel = new JLabel("This is the text in the label.");
outputPane.add(newLabel);
Once again, because of Java’s use of abstraction, we don’t need to know the details of what
a JLabelobject contains. We simply accept that it has been properly defined in the Java library,
and that the addmethod uses it appropriately.
Make the Frame Visible on the Screen
The only step that remains to cause our frame to be displayed on the screen is to make it vis-
ible. We do this with a method call associated with the frame:
outputFrame.setVisible(true);
As you can see by the way that the call is written, it is an instance method. If we later call
this method with the argument false, the frame will disappear from the screen.
Now let’s put all the pieces together so that we can see their relationship to each other.
Our list of steps is repeated here as comments in the code.
// Import classes
importjava.awt.*; // Supplies layout manager
importjavax.swing.*; // Supplies JFrame class for output display
public class frameExample ...
...
public static voidmain(String[] args)
{
// Declare a variable of class JFrame
JFrame outputFrame;
Container class A class into
which you can add other
elements
T
E
A
M
F
L
Y
Team-Fly®