import javax.swing.*; import java.awt.*; import java.awt.event.*; public class StyleOptionsPanel extends JPanel { private JLabel saying, fontPrompt; private JCheckBox bold, italic; private JTextField enterSize; private int fontSize, style; private JPanel panelCheckBox, panelTextField; //----------------------------------------------------------------- // Sets up a panel with a label and some check boxes that // control the style of the label's font. //----------------------------------------------------------------- public StyleOptionsPanel() { fontSize = 36; style = Font.PLAIN; saying = new JLabel ("Say it with style!"); saying.setFont (new Font ("Helvetica", style, fontSize)); fontPrompt = new JLabel("Enter font size: "); enterSize = new JTextField (4); bold = new JCheckBox ("Bold"); bold.setBackground (Color.cyan); italic = new JCheckBox ("Italic"); italic.setBackground (Color.cyan); panelCheckBox = new JPanel(); panelCheckBox.add(bold); panelCheckBox.add(italic); panelCheckBox.setBackground (Color.cyan); StyleListener listener = new StyleListener(); bold.addItemListener (listener); italic.addItemListener (listener); panelTextField = new JPanel(); panelTextField.add(fontPrompt); panelTextField.add(enterSize); panelTextField.setBackground (Color.cyan); enterSize.addActionListener (new EnterFontListener()); add (saying); add (panelCheckBox); add (panelTextField); setBackground (Color.cyan); setPreferredSize (new Dimension(300, 100)); } //***************************************************************** // Represents the listener for both check boxes. //***************************************************************** private class StyleListener implements ItemListener { //-------------------------------------------------------------- // Updates the style of the label font style. //-------------------------------------------------------------- public void itemStateChanged (ItemEvent event) { style = Font.PLAIN; if (bold.isSelected()) // true when bold checkbox is checked style = Font.BOLD; if (italic.isSelected()) style += Font.ITALIC; saying.setFont (new Font ("Helvetica", style, fontSize)); } } private class EnterFontListener implements ActionListener{ public void actionPerformed(ActionEvent event){ fontSize = Integer.parseInt(enterSize.getText()); saying.setFont (new Font("Helvetica", style, fontSize)); } } }