Java Reference
In-Depth Information
a text-based interface for the music player, effectively replacing the MusicPlayerGUI class
and leaving the MusicPlayer class unchanged.
Inheriting from JFrame
In this example, we are demonstrating the alternative popular version of creating frames that we men-
tioned at the start of the chapter. Our GUI class does not instantiate a JFrame object; instead, it extends
the JFrame class. As a result, all the JFrame methods we need to call (such as getContentPane ,
setJMenuBar , pack , setVisible , and so on) can now be called as internal (inherited) methods.
There is no strong reason for preferring one style (using a JFrame instance) over the other (in-
heriting from JFrame ). It is largely a matter of personal preference, but you should be aware
that both styles are widely used.
Displaying static images
It is very common that we want to display an image in a GUI. The easiest way to do this is to
include in the interface a JLabel that has a graphic as its label (a JLabel can display either text
or a graphic or both). The sound player includes an example of doing this. The relevant source
code is
JLabel image = new JLabel(new ImageIcon(“title.jpg”));
This statement will load an image file named “title.jpg” from the project directory, create an
icon with that image, and then create a JLabel that displays the icon. (The term “icon” seems
to suggest that we are dealing only with small images here, but the image can in fact be of any
size.) This method works for JPEG, GIF, and PNG images.
Combo boxes
The sound player presents an example of using a JComboBox . A combo box is a set of values,
one of which is selected at any time. The selected value is displayed, and the selection can be
accessed through a pop-up menu. In the sound player, the combo box is used to select a particu-
lar ordering for the tracks—by artist, title, etc.
A JComboBox may also be editable, in which case the values are not all predefined but can be
typed by a user. Ours is not.
Lists
The program also includes an example of a list (class JList ) for the list of tracks. A list can
hold an arbitrary number of values, and one or more can be selected. The list values in this
example are strings, but other types are possible. A list does not automatically have a scrollbar.
Scrollbars
Another component demonstrated in this example is the use of scrollbars.
Scrollbars can be created by using a special container, an instance of class JScrollPane . GUI
objects of any type can be placed into a scroll pane, and the scroll pane will, if the held object is
too big to be displayed in the available space, provide the necessary scrollbars.
 
Search WWH ::




Custom Search