/* * File: TempConvUsingInnerClasses.java * ------------------------------------ * This program allows users to convert temperatures back * and forth from Fahrenheit to Celsius. This version uses * anonymous inner classes to specify the action listeners. */ import acm.gui.*; import acm.program.*; import java.awt.event.*; import javax.swing.*; /** This class implements a simple temperature converter */ public class TempConvUsingInnerClasses extends Program { /** Initialize the graphical user interface */ public void init() { setLayout(new TableLayout(2, 3)); fahrenheitField = new IntField(32); celsiusField = new IntField(0); ActionListener convertFToC = new ActionListener() { public void actionPerformed(ActionEvent e) { int f = fahrenheitField.getValue(); int c = (int) Math.round( (5.0 / 9.0) * (f - 32) ); celsiusField.setValue(c); } }; ActionListener convertCToF = new ActionListener() { public void actionPerformed(ActionEvent e) { int c = celsiusField.getValue(); int f = (int) Math.round( (9.0 / 5.0) * c + 32 ); fahrenheitField.setValue(f); } }; JButton convertFToCButton = new JButton("F -> C"); JButton convertCToFButton = new JButton("C -> F"); fahrenheitField.addActionListener(convertFToC); celsiusField.addActionListener(convertCToF); convertFToCButton.addActionListener(convertFToC); convertCToFButton.addActionListener(convertCToF); add(new JLabel("Degrees Fahrenheit")); add(fahrenheitField); add(convertFToCButton); add(new JLabel("Degrees Celsius")); add(celsiusField); add(convertCToFButton); } /* Private instance variables */ private IntField fahrenheitField; private IntField celsiusField; /** Set the program dimensions */ public static final int APPLICATION_WIDTH = 300; public static final int APPLICATION_HEIGHT = 200; /* Standard Java entry point */ /* This method can be eliminated in most Java environments */ public static void main(String[] args) { new TempConvUsingInnerClasses().start(args); } }