// RepaintandValidateGrades.java // Counting letter grades import java.awt.*; import javax.swing.*; import java.awt.event.*; public class RepaintandValidateGrades extends JApplet implements ActionListener { JLabel prompt; // label for text field input JTextField input; // text field to enter grades JLabel correction_prompt; // label for text field correction_display JTextField correction_display; // text field to show erroneous grades JPanel inter; // panel for interaction with the user JPanel message; // panel for writing grades status boolean correction_present; int aCount = 0, bCount = 0, cCount = 0, dCount = 0, fCount = 0; Container c; public void init() { c = getContentPane(); c.setLayout ( new GridLayout (2,1, 10, 10) ); inter = new JPanel(); inter.setLayout (new GridLayout(1,2)); prompt = new JLabel( "Enter grade" ); input = new JTextField( 2 ); input.addActionListener( this ); inter.add( prompt ); inter.add( input ); message = new JPanel(); c.add( inter ); c.add( message ); correction_present = false; } public void paint( Graphics g ) { g.drawString( "Totals for each letter grade:", 25, 180 ); g.drawString( "A: " + aCount, 25, 195 ); g.drawString( "B: " + bCount, 25, 210 ); g.drawString( "C: " + cCount, 25, 225 ); g.drawString( "D: " + dCount, 25, 240 ); g.drawString( "F: " + fCount, 25, 255 ); } public void actionPerformed( ActionEvent e ) { String val = e.getActionCommand(); char grade = val.charAt( 0 ); showStatus( "" ); // clear status bar area input.setText( "" ); // clear input text field // removing correction components if ( correction_present ) { inter.remove (correction_prompt); inter.remove (correction_display); inter.setLayout (new GridLayout(1,2)); correction_present = false; }; switch ( grade ) { case 'A': case 'a': // Grade was uppercase A ++aCount; // or lowercase a. break; case 'B': case 'b': // Grade was uppercase B ++bCount; // or lowercase b. break; case 'C': case 'c': // Grade was uppercase C ++cCount; // or lowercase c. break; case 'D': case 'd': // Grade was uppercase D ++dCount; // or lowercase d. break; case 'F': case 'f': // Grade was uppercase F ++fCount; // or lowercase f. break; default: // catch all other characters showStatus( "Incorrect grade. Enter new grade." ); correction_prompt = new JLabel( "You entered an incorrect grade:" ); correction_display = new JTextField( new Character(grade).toString() ); inter.setLayout(new GridLayout(2,2)); inter.add (correction_prompt); inter.add (correction_display); validate(); // show new GUIs correction_present = true; break; } c.repaint(); repaint(); // display summary of results } }