Java Reference
In-Depth Information
JButton add - but = new Jbutton ( " Add " );
JButton mult - but = new Jbutton ( " Mult " );
// Put a button in each grid cell
add (add - but);
add (mult - but);
} // ctor
} // class ActionButtonsPanel
Note that the buttons here do nothing when clicked. We explain in Chapter 7 how
to add actions to buttons and other active components.
6.5.2 More about components and laying them out
We introduced the JButton and JPanel user interface components in the pre-
vious section. Two other components commonly needed are:
JLabel - for text and icon labels
JTextField -toprovide for input and output of text in a single line display
For both components you can pass a string via a constructor parameter to provide
the initial text. The classes contain a number of methods but the two primary
ones for basic operation are:
public String getText ()
public void setText (String str)
While Jlabel objects do not interact with the user, JTextField is an active
component like JButton that can respond to user actions. We discuss adding
behavior to text fields in Chapter 7. You can allow or disallow user modification
of the text in a text field display by invoking setEnabled (boolean flag) .
An enabled state of true means that the text can be modified while false
prevents modification.
For our next applet we want to create a subclass of JPanel with two text
fields. We put labels beside each so that the user can identify the text field. To
insure that the labels and text fields are arranged in a logical manner we need to
use a layout manager .
Java interfaces require great flexibility in how they arrange the components.
The interfaces must be portable to different platforms and graphical environments
and to displays with different screen sizes and resolutions. The width and height
of the container may change with the tag settings for an applet or by the user
shrinking or expanding an application window.
For these reasons absolute positioning is not suitable for Java GUIs. Instead, a
Java container uses one of the several layout manager classes, which arrange the
components according to general design guidelines rather than fixed coordinate
settings. We discuss layout managers in more detail in Chapter 7 but for the
example programs here we introduce two of the simplest layout managers:
 
Search WWH ::




Custom Search