import java.awt.* ;
import java.awt.event.*;
public class percentFat extends Frame implements ActionListener
{
Label title = new Label("Percent of Calories from Fat");
Label fatLabel = new Label("Enter grams of fat: ");
Label calLabel = new Label("Enter total calories: ");
Label perLabel = new Label("Percent calories from fat: ");
TextField inFat = new TextField( 7 );
TextField inCal = new TextField( 7 );
TextField outPer = new TextField( 7 );
Button doit = new Button("Do It!");
int calories ; // input from the user: total calories per serving
int fatGrams ; // input from the user: grams of fat per serving
double percent ; // result: percent of calories from fat
percentFat() // constructor
{
setTitle("Calories from Fat");
setLayout( new FlowLayout() ); // choose the layout manager
add( title );
add( fatLabel );
add( inFat );
add( calLabel );
add( inCal );
add( perLabel );
add( outPer );
outPer.setEditable( false );
add( doit );
doit.addActionListener( this );
}
// The application
public void calcPercent( )
{
percent = ( (fatGrams * 9.0) / calories ) * 100.0 ;
}
public void actionPerformed( ActionEvent evt)
{
String userIn ;
userIn = inFat.getText() ;
fatGrams = Integer.parseInt( userIn ) ;
userIn = inCal.getText() ;
calories = Integer.parseInt( userIn ) ;
calcPercent() ;
outPer.setText( percent+" " );
repaint();
}
public static void main ( String[] args )
{
percentFat fatApp = new percentFat() ;
WindowQuitter wquit = new WindowQuitter();
fatApp.addWindowListener( wquit );
fatApp.setSize( 280, 200 );
fatApp.setVisible( true );
}
}
class WindowQuitter extends WindowAdapter
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
|