// WindowPractice1.java // Practice with anonymous inner classes, JFrame, windows, WindowAdapter import java.text.DecimalFormat; import java.awt.event.*; import java.awt.*; import javax.swing.*; public class WindowPractice1 extends JFrame { DecimalFormat precision2 = new DecimalFormat( "0.00" ); private double length, width; private JLabel lengthLabel, widthLabel, areaLabel; private JTextField lengthField, widthField, areaField; // constructor public WindowPractice1( ) { super ( "Anonymous Inner Class Practice" ); Container c = getContentPane( ); c.setLayout( new FlowLayout( ) ); lengthLabel = new JLabel( "Enter the length:" ); lengthField = new JTextField( 10 ); lengthField.addActionListener( new ActionListener( ) { // anonymous inner class begins public void actionPerformed( ActionEvent e ) { calcArea( ); } } // anonymous inner class ends ); c.add( lengthLabel ); c.add( lengthField ); widthLabel = new JLabel( "Enter the width:" ); widthField = new JTextField( 10 ); widthField.addActionListener( new ActionListener( ) { // anonymous inner class begins public void actionPerformed( ActionEvent e ) { calcArea( ); } } // anonymous inner class ends ); c.add( widthLabel ); c.add( widthField ); areaLabel = new JLabel( "Area of the rectangle" ); areaField = new JTextField( 10 ); areaField.setEditable( false ); c.add( areaLabel ); c.add( areaField ); } public void calcArea( ) { length = Double.parseDouble( lengthField.getText( ) ); width = Double.parseDouble( widthField.getText( ) ); areaField.setText( precision2.format( length * width ) ); } public static void main( String args[ ] ) { WindowPractice1 w = new WindowPractice1( ); w.addWindowListener( new WindowAdapter( ) { // anonymous inner class begins public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } // anonymous inner class ends ); w.setSize( 300, 150 ); w.show( ); } }