Java Reference
In-Depth Information
}
}
class
NotepadFrame
extends
JFrame
{
private static int
WIDTH = 600;
private static int
HEIGHT = 600;
public
NotepadFrame ()
{
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.DISPOSEON CLOSE) ;
JTextArea textArea =
new
JTextArea () ;
add(
new
JScrollPane(textArea) ,BorderLayout.CENTER) ;
}
}
If you run the application, you will see a text area where one can enter text. Scroll bars
appear only when the text is too big to be displayed in the window. Note that the code
BorderyLayout.CENTER
is optional because by default a component is added in the center
when the border layout is used and border layout is the default layout for frames. Similar to
the
JTextField
class, the
JTextArea
class supports the
getText
and
setText
methods for
getting and setting the text. Note that both methods work with strings, where a string can
contain multiple lines that are separated by the character
. In addition, the
JTextArea
class supports the
append
method for appending text to the
JTextArea
class.
'
\
n'
12.7 The Combo Box
Our Notepad application looks pretty basic even for a poor man's version. To make the
program more interesting, we will next add a feature for changing the font of the text; see
Figure 12.4. As the figure suggests, we will add a panel to the north part of the window.
In the panel, we will add a combo box that displays all the fonts that are supported by the
operating system.
First, we need to determine the fonts that are available from the operating system. The
following expression will give us this set as an array of strings.
String [ ] fontNames = GraphicsEnvironment . getLocalGraphicsEnvironment () .
getAvailableFontFamilyNames () ;
Next, we will create a combo box, which is also known as a drop-down list. We can
use the empty constructor of the
JComboBox
class to create a combo box and then add the
elements using the
addItem
method. Alternatively, an array of objects can be specified in
the constructor. The
getSelectedItem
method can be used on a combo box to find the
item that is selected, where the method returns an object of type
Object
.
Next, let us examine the
Font
class, which is used to create a new font.
The most common constructor of the
Font
class takes as input three parameters:
the name of the font, the style of the text (e.g., bold), and the point size of the font.
Possible values for the style of the text include
Font.PLAIN
,
Font.BOLD
,
Font.Italic
,
where values can be combined by adding them. For example,
Font.Bold+Font.Italic
creates style that is both bold and italic.