package examples; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * CS401 Example 36 * * Demonstrates the use of JCheckBox GUI components. The program displays a * JLabel containing some text and provides two JCheckBox buttons to allow the * user to dynamically make the text bold, italics, bold and italics, or plain. * * Note that JCheckBoxes fire a different kind of event when the user clicks on * them, an ItemEvent. This then requires a different kind of Listener, which * the program now implements. The ItemListener interface defines only a single * method, itemStateChanged(ItemEvent e), which is called when an ItemEvent * object is generated by the GUI. * * @author PJ Dillon */ public class ex36 implements ItemListener { private JLabel label; private JCheckBox bold, italic; private Font font; public ex36() { JFrame window = new JFrame("Example 36"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = window.getContentPane(); c.setLayout(new FlowLayout()); font = new Font("TimesRoman", Font.PLAIN, 72); label = new JLabel("Text To Change"); label.setFont(font); c.add(label); /* * Declare the JCheckBoxes */ bold = new JCheckBox("Bold"); c.add(bold); italic = new JCheckBox("Italics"); c.add(italic); //Register this object to listen for ItemEvents bold.addItemListener(this); italic.addItemListener(this); window.setSize(520, 200); window.setVisible(true); } public void itemStateChanged(ItemEvent e) { /* * The constants for setting a font's style are defined in such a way so as * to allow each kind of style to be added or subtracted from an overall * 'style' value. Thus, with each change in the state of a JCheckBox, we * want to add or subject the proper style from the current one. */ //get the current style int style = font.getStyle(); /* * The ItemEvent class defines the getStateChange() method, which acesses * the new state of the object that generated the ItemEvent. The return * value can be compared with one of two constants defined in the ItemEvent * class, SELECTED and DESELECTED. If the JCheckBox has become SELECTED, the * user wishes to make the text either bold or italic. Otherwise, we need to * remove the bold or italics style from the font. We can know which style * the user wants to change by knowing which JCheckBox generated the event. */ if(e.getStateChange() == ItemEvent.SELECTED) { if(e.getSource() == bold) style += Font.BOLD; else if(e.getSource() == italic) style += Font.ITALIC; } else { if(e.getSource() == bold) style -= Font.BOLD; else if(e.getSource() == italic) style -= Font.ITALIC; } font = new Font("TimesRoman", style, 72); label.setFont(font); label.repaint(); } public static void main(String[] args) { new ex36(); } }