Java Reference
In-Depth Information
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 ( ) ;
final
JCheckBox boldCheckBox =
new
JCheckBox(
"Bold"
);
final
JCheckBox italicCheckBox =
new
JCheckBox(
"Italic"
);
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)
{
int
mask = Font .PLAIN;
if
(boldCheckBox . isSelected () )
{
mask += Font .BOLD;
if
(italicCheckBox . isSelected ())
{
mask += Font . ITALIC;
textArea . setFont(
new
Font((String) fontComboBox. getSelectedItem
() , mask, (Integer) sizeComboBox. getSelectedItem())) ;
}
}
;
fontComboBox. addActionListener(changeListener) ;
sizeComboBox. addActionListener(changeListener) ;
boldCheckBox. addActionListener(changeListener) ;
italicCheckBox . addActionListener(changeListener) ;
controlPanel . add( fontComboBox) ;
controlPanel .add(sizeComboBox) ;
controlPanel . add(boldCheckBox) ;
controlPanel .add(italicCheckBox) ;
add( controlPanel , BorderLayout .NORTH) ;
}
}
Note that the mask of the font is set based on the state of the bold and italic check
boxes. Note as well that a single action listener is associated with the two combo boxes and
the two check boxes. The reason is that a single event handler is responsible for changing
the font. The
actionPerformed
method sets the font, the size of the font, and its style.