Java Reference
In-Depth Information
Exercise 11.49
Properly implement the
makeSmaller
and
makeLarger
methods. To do
this, you have to create a new
OFImage
with a different size, copy the pixels from the current
image across (while scaling it up or down), and then set the new image as the current image.
At the end of your method, you should call the frame's
pack
method to rearrange the compo-
nents with the changed size.
Exercise 11.50
All Swing components have a
setEnabled(boolean)
method that can
enable and disable the component. Disabled components are usually displayed in light gray
and do not react to input. Change your image viewer so that the two toolbar buttons are ini-
tially disabled. When an image is opened, they should be enabled, and when it is closed, they
should be disabled again.
11.7.2
Borders
The last polish we want to add to our interface is some internal borders. Borders can be used to group
components or just to add some space between them. Every Swing component can have a border.
Some layout managers also accept constructor parameters that define their spacing, and the lay-
out manager will then create the requested space between components.
The most used borders are
BevelBorder
,
CompoundBorder
,
EmptyBorder
,
EtchedBorder
,
and
TitledBorder
. You should familiarize yourself with these.
We shall do three things to improve the look of our GUI:
■
add some empty space around the outside of the frame
■
add spacing between the components of the frame
■
add a line around the image
The code to do this is shown in Code 11.16. The
setBorder
call on the content pane with an
EmptyBorder
as a parameter adds empty space around the outside of the frame. Note that we
now cast the
contentPane
to a
JPanel
, as the supertype
Container
does not have the
set-
Border
method.
6
Code 11.16
Adding spacing with
gaps and borders
JPanel contentPane = (JPanel) frame.getContentPane();
contentPane.setBorder(
new
EmptyBorder(12, 12, 12, 12));
// Specify the layout manager with nice spacing.
contentPane.setLayout(
new
BorderLayout(6, 6));
imagePanel =
new
ImagePanel();
imagePanel.setBorder(
new
EtchedBorder());
contentPane.add(imagePanel, BorderLayout.CENTER);
6
Using a cast in this way only works because the dynamic type of the content pane is already
JPanel
.
The cast does not transform the content-pane object into a
JPanel
in any sense.
Search WWH ::
Custom Search