Java Reference
In-Depth Information
class
NotepadFrame
extends
JFrame
{
private static int
WIDTH = 600;
private static int
HEIGHT = 600;
public
NotepadFrame ()
{
setDefaultCloseOperation(JFrame.DISPOSEON CLOSE) ;
setSize(WIDTH,HEIGHT);
final
JTextArea textArea =
new
JTextArea () ;
add(
new
JScrollPane(textArea) ,BorderLayout.CENTER) ;
JPanel controlPanel =
new
JPanel () ;
controlPanel . setLayout(
new
FlowLayout(FlowLayout .LEFT) ) ;
String [ ] fontNames = GraphicsEnvironment .
getLocalGraphicsEnvironment () .
getAvailableFontFamilyNames () ;
final
JComboBox fontComboBox =
new
JComboBox(fontNames) ;
fontComboBox. setSelectedItem(
"SansSerif"
);
final
JComboBox sizeComboBox =
new
JComboBox ( ) ;
for
(
int
i=8;i
<
= 72; i++)
{
sizeComboBox . addItem( i ) ;
sizeComboBox. setSelectedItem(12) ;
sizeComboBox . setEditable (
true
);
ActionListener changeListener =
new
ActionListener ()
{
public void
actionPerformed(ActionEvent e)
{
textArea . setFont(
new
Font (( String ) fontComboBox .
getSelectedItem() ,Font.PLAIN,( Integer)sizeComboBox.
getSelectedItem())) ;
}
}
;
fontComboBox. addActionListener(changeListener) ;
sizeComboBox. addActionListener(changeListener) ;
controlPanel . add( fontComboBox) ;
controlPanel .add(sizeComboBox) ;
add( controlPanel , BorderLayout .NORTH) ;
}
}
The font of the text area is set by calling the
setFont
method.Notethatthevariable
textArea
is defined as final because it is referenced in a local anonymous class. Note that
the
setSelectedItem
method is used to set a default font and default size for the text. The
method takes as input an object and selects that object in the combo box. Note as well that
there is a
getSelectedItem
method that returns the selected element of the combo box.
Since the method returns an object, a cast to the appropriate type is needed (in our case,
to
String
and to
Integer
). The
setEditable
method can make the combo box editable
or not editable. If the combo box is editable, then the user can type text in the combo box.
Otherwise, they can just selected one of the available menu options. By default, a combo
box is not editable. By making the
size
combo box editable, we have allowed the user to
type in the size of the font.
Note that inside the
actionPerformed
method we directly referred to the combo box. If
we did not have access to the combo box, then we could have used the call
e.getSource()
to get the source of the action listener event.