Java Reference
In-Depth Information
All of the classes
JButton, JMenuItem,
and
JLabel
have constructors that let you
specify text and an icon to appear on the button, menu item, or label. The constructor
can specify no text or icon, text only, an icon only, or both text and an icon. When you
specify both text and an icon, the text is the first argument and the icon is the second
argument; also, the constructor for a
JLabel
requires a third argument, as described in
Display 18.5. If you omit either text or an icon (or both) from the constructor, you can
add them later with the methods
setText
and
setIcon.
Some of these methods for
the classes
JButton, JMenuItem,
and
Jlabel
are given in Display 18.5 .
Icons and the Class
ImageIcon
An
icon
is simply a small picture, although it is not really required to be small. The class
ImageIcon
is used to convert a picture file to a Swing icon.
SYNTAX
ImageIcon
Name_Of_ImageIcon
=
new
ImageIcon(Picture_File_Name);
The
Picture_File_Name
is a string giving either a relative or absolute path name to the
picture file. (So if the picture file is in the same directory as your program, you need give
only the name of the picture file.)
EXAMPLE
ImageIcon happyIcon =
new
ImageIcon("smiley.gif");
Display 18.5
Some Methods in the Classes
JButton
,
JMenuItem
, and
JLabel
(part 1 of 2)
public
JButton()
public
JMenuItem()
public
JLabel()
Creates a button, menu item, or label with no text or icon on it. (Typically, you will later use
setText
and/or
setIcon
with the button, menu item, or label.)
public
JButton(String text)
public
JMenuItem(String text)
public
JLabel(String text)
Creates a button, menu item, or label with the text on it.
public
JButton(ImageIcon picture)
public
JMenuItem(ImageIcon picture)
public
JLabel(ImageIcon picture)
Creates a button, menu item, or label with the icon
picture
on it and no text.
(continued)