Java Reference
In-Depth Information
background colour of a label one has to first make it opaque (non-transparent)
using the method setOpaque .
setOpaque(boolean b) makes the label transparent if b is false and non-
transparent if b is true .
3.3.2
Buttons
Buttons are rectangular areas (usually with a line around) which - like labels -
can display text. They differ from labels in the fact that they can trigger events .
An event occurs whenever a button is pressed. The Java runtime system monitors
buttons and recognizes when such an event occurs. Note that a button is not
necessarily pressed by clicking the mouse, it might also be a finger on a touch
screen monitor. Therefore, buttons are treated separately from the mouse.
In Section 3.4 we shall learn in detail how the runtime system informs our
program that an event has occurred. For now, the following explanation should
suffice: in order to notice when a button is pressed, something has to keep an eye
on the button. This is done by a listener ,a(non-graphical) component from the
AWT library. The listener has to be assigned to the button in order to monitor
it. If an event occurs at that button the runtime system informs the listener. The
listener can then analyse the event and initiate a certain action.
Class JButton implements buttons in Swing. We only present the constructor
and the method to assign a listener to the button.
public JButton(String text);
public void addActionListener(ActionListener listener);
3.3.3
Constructing the graphics
We use two buttons to change the value of the counter and a label to display
its value. There are many ways to arrange these components. One would be to
'glue' the buttons and the label directly into the content pane of the frame. We
use a different approach here: an intermediate panel into which the buttons and
the label are embedded. The corresponding class is called CounterPanel . Then
a CounterPanel is glued into the frame; see Figure 3.2. The advantage of this
approach is that one can reuse the CounterPanel as a ready-made module in
other applications.
We first have to decide which layout manager supports the intended GUI. In
our case, a border layout is appropriate for both the panel and the frame. We glue
the buttons into the west and east positions of the panel and glue the label into
the central one. Actually, panels have a border layout by default. We nevertheless
set the layout to make clear that this is one step of a GUI implementation.
Every CounterPanel holds its own instance of CounterModel in the variable
counter . This variable is private so that the counter cannot be manipulated di-
rectly from outside the class CounterPanel . Instead CounterPanel offers two
methods, increment() and decrement() , which simply call the respective meth-
ods of counter model counter .
Search WWH ::




Custom Search