/* COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved. This class builds the GPA calculator GUI. @site http://www.javaika.com @author Alexander Wait @version 2011-07-18 */ import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.*; import javax.swing.*; public class GpaCalculatorGui extends JApplet implements ComponentListener, FocusListener { private static final String copyright = "Copyright (c) 2012 by Alexander Wait - All Rights Reserved"; private static final long serialVersionUID = 1L; static boolean isApplication = false; static boolean isVisible = false; private static final int THREE_YEAR_FACTOR = 3; private static final int FRAME_SIZE_X = 580; private static final int FRAME_SIZE_Y = 500; private enum State {INITIAL, YEARLY_UNITS, NUMBER_SCALE, LETTER_SCALE} //************************************** START INITIALISATION CODE **************************************// /** * Browser constructor. */ public void init() { String copyrightParam = getParameter("copyright"); if ((copyrightParam == null) || !copyrightParam.equals(copyright)) { Message.showMessage("Invalid Copyright", "WARNING", "warning"); } else if (!getDocumentBase().getHost().equals(Domain.getDomain())) { Message.showMessage("Unauthorised Applet Use", "ERROR", "error"); } else { initialiser(); includeResizeEvent(); setSize(FRAME_SIZE_X,FRAME_SIZE_Y); } } /** * Application constructor. */ public GpaCalculatorGui() { if (isApplication) { initialiser(); frame = new JFrame(); frame.setMinimumSize(new Dimension(FRAME_SIZE_X, FRAME_SIZE_Y)); frame.setSize(FRAME_SIZE_X,FRAME_SIZE_Y); frame.setLocationRelativeTo(null); frame.setTitle("GPA Program"); frame.add(contentPane); setVisibility(); } } /** * GUI initializer. * ESCA-JAVA0076: */ private void initialiser() { grades = new GpaCalculator(); valid = new Validation(); // Initialize content pane and layout. contentPane = getContentPane(); contentPane.setLayout(new GridBagLayout()); // Initialize JLabel GUI components. firstPrompt = new JLabel (" STEP 1 : Tick 'yes' if you are using percentage grades (%) to calculate your GPA"); firstPrompt.setFont(new Font("Serif", Font.BOLD, 13)); secondPrompt = new JLabel (" STEP 2 : Write the total number of credit points per year for a normal full time load"); secondPrompt.setFont(new Font("Serif", Font.BOLD, 13)); thirdPrompt = new JLabel (" STEP 3 : Select the letter grading scale reported on your statement of results"); thirdPrompt.setFont(new Font("Serif", Font.BOLD, 13)); fourthPrompt = new JLabel (" STEP 4 : Select the GPA scale your college uses"); fourthPrompt.setFont(new Font("Serif", Font.BOLD, 13)); fifthPrompt = new JLabel (" Enter course information in order starting from most recently completed"); fifthPrompt.setFont(new Font("Serif", Font.BOLD, 13)); // Initialize text field GUI components. unitsPerYear = new JTextField(); unitsPerYear.setText("Type Here"); unitsPerYear.setPreferredSize(new Dimension(100, 22)); unitsPerYear.setFont(new Font("Serif", Font.BOLD, 12)); unitsPerYear.setHorizontalAlignment(JTextField.CENTER); unitsPerYear.addFocusListener(this); courseName = new JTextField(); courseName.setText("Course Name"); courseName.setPreferredSize(new Dimension(100, 22)); courseName.setFont(new Font("Serif", Font.BOLD, 12)); courseName.setHorizontalAlignment(JTextField.CENTER); courseName.addFocusListener(this); unitValue = new JTextField(); unitValue.setText("Unit Value"); unitValue.setPreferredSize(new Dimension(100, 22)); unitValue.setFont(new Font("Serif", Font.BOLD, 12)); unitValue.setHorizontalAlignment(JTextField.CENTER); unitValue.addFocusListener(this); courseGrade = new JTextField(); courseGrade.setText("Course Grade"); courseGrade.setPreferredSize(new Dimension(100, 22)); courseGrade.setFont(new Font("Serif", Font.BOLD, 12)); courseGrade.setHorizontalAlignment(JTextField.CENTER); courseGrade.addFocusListener(this); courseWeight = new JTextField(); courseWeight.setText("Course Weight"); courseWeight.setPreferredSize(new Dimension(100, 22)); courseWeight.setFont(new Font("Serif", Font.BOLD, 12)); courseWeight.setHorizontalAlignment(JTextField.CENTER); courseWeight.addFocusListener(this); gpaField = new JTextField(); gpaField.setEditable(false); gpaField.setPreferredSize(new Dimension(100, 22)); gpaField.setFont(new Font("Serif", Font.BOLD, 12)); gpaField.setHorizontalAlignment(JTextField.CENTER); gpaField.setText("GPA"); wamField = new JTextField(); wamField.setEditable(false); wamField.setPreferredSize(new Dimension(100, 22)); wamField.setFont(new Font("Serif", Font.BOLD, 12)); wamField.setHorizontalAlignment(JTextField.CENTER); wamField.setText("WAM"); // Initialize text area GUI components. display = new JTextArea(); display.setEditable(false); // Initialize scroll pane GUI components. scrollPane = new JScrollPane(display, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setPreferredSize(new Dimension(100,330)); // Initialize radio button GUI components. australianLetterScale = new JRadioButton("HD, D, C, P, F", true); australianLetterScale.addItemListener(new LetterScaleHandlerClass()); australianLetterScale.setFocusPainted(false); americanLetterScale = new JRadioButton("A, B, C, D, F", true); americanLetterScale.addItemListener(new LetterScaleHandlerClass()); americanLetterScale.setFocusPainted(false); fourScale = new JRadioButton("Scale (0 - 4)", true); fourScale.setFocusPainted(false); fourScale.addItemListener(new NumberScaleHandlerClass()); sevenScale = new JRadioButton("Scale (0 - 7)", true); sevenScale.setFocusPainted(false); sevenScale.addItemListener(new NumberScaleHandlerClass()); // Initialize check box GUI components. threeYearCheck = new JCheckBox (" Enforce GPA calculation on the most recent 3 full time equivalent years" , false); threeYearCheck.addItemListener(new ThreeYearsHandlerClass()); threeYearCheck.setFocusPainted(false); yesPercentageCheck = new JCheckBox(" YES ", false); yesPercentageCheck.addItemListener(new PercentageHandlerClass()); yesPercentageCheck.setFocusPainted(false); // Initialize button GUI components. nextButton = new JButton(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorNextNormal.png")) ); nextButton.setRolloverIcon(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorNextRollover.png")) ); nextButton.setPressedIcon(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorNextPressed.png")) ); nextButton.setBorder(BorderFactory.createEmptyBorder(0,0,0,0)); nextButton.setPreferredSize(new Dimension(99, 21)); nextButton.addActionListener(new NextButtonListener()); addButton = new JButton(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorAddNormal.png")) ); addButton.setRolloverIcon(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorAddRollover.png")) ); addButton.setPressedIcon(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorAddPressed.png")) ); addButton.setBorder(BorderFactory.createEmptyBorder(0,0,0,0)); addButton.setPreferredSize(new Dimension(99, 21)); addButton.addActionListener(new AddButtonListener()); clearButton = new JButton(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorClearNormal.png")) ); clearButton.setRolloverIcon(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorClearRollover.png")) ); clearButton.setPressedIcon(new ImageIcon(this.getClass().getResource ( "files/images/GradesCalculatorClearPressed.png")) ); clearButton.setBorder(BorderFactory.createEmptyBorder(0,0,0,0)); clearButton.setPreferredSize(new Dimension(99, 21)); clearButton.addActionListener(new ClearButtonListener()); // Initialize JPanel GUI components. scaleTypeContainer = new JPanel(); scaleTypeContainer.setLayout(new GridLayout(2,1)); scaleTypePanel = new JPanel(); scaleTypePanel.setLayout(new GridLayout(1,2)); courseInfoPanel = new JPanel(); courseInfoPanel.setLayout(new FlowLayout()); bottomPanel = new JPanel(); bottomPanel.setLayout(new GridLayout(1,2)); clearPanel = new JPanel(); clearPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); gradePanel = new JPanel(); gradePanel.setLayout(new FlowLayout()); leftPanel = new JPanel(); leftPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); rightPanel = new JPanel(); rightPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); rightPanel.setPreferredSize(new Dimension(266, 35)); leftPanel.setPreferredSize(new Dimension(266, 35)); // Add GUI components to JPanels. clearPanel.add(clearButton); gradePanel.add(gpaField); bottomPanel.add(gradePanel); bottomPanel.add(clearPanel); gradePanel.add(wamField); courseInfoPanel.add(courseName); leftPanel.add(yesPercentageCheck); rightPanel.add(nextButton); scaleTypePanel.add(leftPanel); scaleTypePanel.add(rightPanel); courseInfoPanel.add(unitValue); courseInfoPanel.add(courseGrade); courseInfoPanel.add(courseWeight); courseInfoPanel.add(addButton); scaleTypeContainer.add(scaleTypePanel); scaleTypeContainer.add(firstPrompt); // Initialize starter points. useAustralianLetterScale = true; useSevenScale = false; state = State.INITIAL; // Method calls for GUI initialization. gridBagConstraints(); setColors(); setGraphicIcons(); } /** * Sets the background color. */ private void setColors() { contentPane.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); yesPercentageCheck.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); leftPanel.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); rightPanel.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); courseInfoPanel.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); bottomPanel.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); clearPanel.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); gradePanel.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); scaleTypeContainer.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); australianLetterScale.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); americanLetterScale.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); unitsPerYear.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); fourScale.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); sevenScale.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); threeYearCheck.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); courseName.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); unitValue.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); courseGrade.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); courseWeight.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); gpaField.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); wamField.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); display.setBackground ( new Color (ColorFunctions.red(), ColorFunctions.green(), ColorFunctions.blue()) ); } /** * Sets icons for graphical elements. */ private void setGraphicIcons() { australianLetterScale.setIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonNormalUnselected.png"))); australianLetterScale.setSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonNormalSelected.png"))); australianLetterScale.setDisabledIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonDisabledUnselected.png"))); australianLetterScale.setDisabledSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonDisabledSelected.png"))); americanLetterScale.setIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonNormalUnselected.png"))); americanLetterScale.setSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonNormalSelected.png"))); americanLetterScale.setDisabledIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonDisabledUnselected.png"))); americanLetterScale.setDisabledSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonDisabledSelected.png"))); fourScale.setIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonNormalUnselected.png"))); fourScale.setSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonNormalSelected.png"))); fourScale.setDisabledIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonDisabledUnselected.png"))); fourScale.setDisabledSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonDisabledSelected.png"))); sevenScale.setIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonNormalUnselected.png"))); sevenScale.setSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonNormalSelected.png"))); sevenScale.setDisabledIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonDisabledUnselected.png"))); sevenScale.setDisabledSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/RadioButtonDisabledSelected.png"))); yesPercentageCheck.setIcon(new ImageIcon (this.getClass().getResource("files/images/CheckBoxNormalUnselected.png"))); yesPercentageCheck.setSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/CheckBoxNormalSelected.png"))); yesPercentageCheck.setDisabledIcon(new ImageIcon (this.getClass().getResource("files/images/CheckBoxDisabledUnselected.png"))); yesPercentageCheck.setDisabledSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/CheckBoxDisabledSelected.png"))); threeYearCheck.setIcon(new ImageIcon (this.getClass().getResource("files/images/CheckBoxNormalUnselected.png"))); threeYearCheck.setSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/CheckBoxNormalSelected.png"))); threeYearCheck.setDisabledIcon(new ImageIcon (this.getClass().getResource("files/images/CheckBoxDisabledUnselected.png"))); threeYearCheck.setDisabledSelectedIcon(new ImageIcon (this.getClass().getResource("files/images/CheckBoxDisabledSelected.png"))); } /** * Sets the grid bag layout. * ESCA-JAVA0076: */ private void gridBagConstraints() { // Initialize grid bag layout of GUI. constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.HORIZONTAL; // Grid bag constraints 1. constraints.insets = new Insets(10,0,0,0); constraints.ipadx = 0; constraints.ipady = 0; constraints.gridwidth = 2; constraints.weightx = 0; constraints.weighty = 0; constraints.gridx = 0; constraints.gridy = 0; contentPane.add(scaleTypeContainer, constraints); // Grid bag constraints 2. constraints.insets = new Insets(10,0,0,0); constraints.ipadx = 0; constraints.ipady = 0; constraints.gridwidth = 2; constraints.weightx = 0; constraints.weighty = 0; constraints.gridx = 0; constraints.gridy = 1; contentPane.add(scrollPane, constraints); } //*************************************** END INITIALISATION CODE ***************************************// //************************************* START INTERFACE EVENT CODE **************************************// private class NextButtonListener implements ActionListener { /** * Listener for the next button. */ public void actionPerformed(ActionEvent event) { if (state.equals(State.INITIAL)) { scaleTypeContainer.remove(firstPrompt); leftPanel.remove(yesPercentageCheck); scaleTypeContainer.add(secondPrompt); leftPanel.add(unitsPerYear); state = State.YEARLY_UNITS; if(skip) {state = State.NUMBER_SCALE;} } else if (state.equals(State.YEARLY_UNITS)) { if (valid.integerValidation(unitsPerYear.getText())) { setYearUnitTotal(Integer.parseInt(unitsPerYear.getText())); leftPanel.remove(unitsPerYear); scaleTypeContainer.remove(secondPrompt); scaleTypeContainer.add(thirdPrompt); leftPanel.add(australianLetterScale); leftPanel.add(americanLetterScale); state = State.LETTER_SCALE; } } else if (state.equals(State.LETTER_SCALE)) { leftPanel.remove(australianLetterScale); leftPanel.remove(americanLetterScale); scaleTypeContainer.remove(thirdPrompt); scaleTypeContainer.add(fourthPrompt); leftPanel.add(fourScale); leftPanel.add(sevenScale); state = State.NUMBER_SCALE; } else if (state.equals(State.NUMBER_SCALE)) { if (skip) { if (valid.integerValidation(unitsPerYear.getText())) { setYearUnitTotal(Integer.parseInt(unitsPerYear.getText())); scaleTypeContainer.remove(scaleTypePanel); scaleTypeContainer.remove(secondPrompt); scaleTypeContainer.add(courseInfoPanel); scaleTypeContainer.add(threeYearCheck); addGradesFooter(); } } else { rightPanel.remove(fourScale); rightPanel.remove(sevenScale); scaleTypeContainer.remove(fourthPrompt); scaleTypeContainer.remove(scaleTypePanel); scaleTypeContainer.add(courseInfoPanel); scaleTypeContainer.add(threeYearCheck); addGradesFooter(); } } if (isApplication) {frame.setVisible(true);} else {contentPane.revalidate();} } } private class AddButtonListener implements ActionListener { private static final int MINIMUM_PERCENTAGE = 0; private static final int MAXIMUM_PERCENTAGE = 100; /** * Listener for the add button. */ public void actionPerformed(ActionEvent event) { if (isApplication) { frame.setVisible(true); } else {contentPane.revalidate();} if (valid.integerValidation(unitValue.getText()) && valid.integerValidation(courseWeight.getText())) { if(usePercentageGrade && valid.integerValidation(courseGrade.getText()) && (MINIMUM_PERCENTAGE <= Integer.parseInt(courseGrade.getText())) && (Integer.parseInt(courseGrade.getText()) <= MAXIMUM_PERCENTAGE)) { calculateGrade(); } else if (!usePercentageGrade) { if(useAustralianLetterScale && grades.isValidLetterGrade(courseGrade.getText(), "australia")) { calculateGrade(); } if((!useAustralianLetterScale) && grades.isValidLetterGrade(courseGrade.getText(), "states")) { calculateGrade(); } } addFieldPlaceholders(); } } } private class ClearButtonListener implements ActionListener { /** * Listener for the clear button. */ public void actionPerformed(ActionEvent event) { grades.resetVariables(); display.setText(null); gpaField.setText("GPA"); wamField.setText("WAM"); } } private class PercentageHandlerClass implements ItemListener { public void itemStateChanged(ItemEvent event) { if (yesPercentageCheck.isSelected()) { skip = true; usePercentageGrade = true; } if (!yesPercentageCheck.isSelected()) { skip = false; usePercentageGrade = false; } } } private class ThreeYearsHandlerClass implements ItemListener { public void itemStateChanged(ItemEvent event) { if (threeYearCheck.isSelected()) { threeYearLimit = true; } else { threeYearLimit = false; } } } private class LetterScaleHandlerClass implements ItemListener { /** * Listener for the radio button. */ private LetterScaleHandlerClass() { ButtonGroup group = new ButtonGroup(); group.add(australianLetterScale); group.add(americanLetterScale); } public void itemStateChanged(ItemEvent event) { if (australianLetterScale.isSelected()) { sevenScale.setEnabled(true); useAustralianLetterScale = true; } if (americanLetterScale.isSelected()) { sevenScale.setEnabled(false); useAustralianLetterScale = false; } } } private class NumberScaleHandlerClass implements ItemListener { /** * Listener for the radio button. */ private NumberScaleHandlerClass() { ButtonGroup group = new ButtonGroup(); group.add(fourScale); group.add(sevenScale); } public void itemStateChanged(ItemEvent event) { if (fourScale.isSelected()) { useSevenScale = false; } if (sevenScale.isSelected()) { useSevenScale = true; } } } public void focusGained(FocusEvent e) { if (unitsPerYear.hasFocus()) { unitsPerYear.setText(null); } if (courseName.hasFocus()) { courseName.setText(null); } if (unitValue.hasFocus()) { unitValue.setText(null); } if (courseGrade.hasFocus()) { courseGrade.setText(null); } if (courseWeight.hasFocus()) { courseWeight.setText(null); } } public void focusLost(FocusEvent e) { if (unitsPerYear.getText().length() == 0) { unitsPerYear.setText("Type Here"); } if (courseName.getText().length() == 0) { courseName.setText("Course Name"); } if (unitValue.getText().length() == 0) { unitValue.setText("Unit Value"); } if (courseGrade.getText().length() == 0) { courseGrade.setText("Course Grade"); } if (courseWeight.getText().length() == 0) { courseWeight.setText("Course Weight"); } } /** * Overrides ComponentListener. */ public void componentMoved(ComponentEvent e) {} public void componentResized(ComponentEvent e) {} public void componentShown(ComponentEvent e) {setContentDisplay(true);} public void componentHidden(ComponentEvent e) {setContentDisplay(false);} //************************************** END INTERFACE EVENT CODE ***************************************// //**************************************** START PUBLIC METHODS *****************************************// /** * Sets the visibility of the frame. */ public void setVisibility() { if (isVisible) { frame.setVisible(true); } else { frame.setVisible(false); } } /** * Displays or Hides contents of GUI. * @param shown */ public void setContentDisplay(boolean shown) { contentPane.setVisible(shown); } //***************************************** END PUBLIC METHODS ******************************************// //**************************************** START PRIVATE METHODS ****************************************// /** * Calculates the grade. */ private void calculateGrade() { display.append(Tools.returnNewline(1)); setCourseName(courseName.getText()); setUnitValue(Integer.parseInt(unitValue.getText())); setUnitWeight(Integer.parseInt(courseWeight.getText())); grades.incrementUnitTotal(getUnitValue()); if (usePercentageGrade) { setCourseGrade(courseGrade.getText()); if ((!threeYearLimit) || (threeYearLimit && (grades.getUnitTotal() <= (getYearUnitTotal() * THREE_YEAR_FACTOR)))) { grades.addSevenAcerPercentage (Integer.parseInt(getCourseGrade()), getUnitValue(), getUnitWeight()); } gpaField.setText(grades.returnSevenScaleGPA() + " / 7.0"); wamField.setText(grades.returnWAM() + " %"); displayCourseInfo(); } else { setCourseGrade(courseGrade.getText()); if (useAustralianLetterScale) { if (useSevenScale) { if ((!threeYearLimit) || (threeYearLimit && (grades.getUnitTotal() <= (getYearUnitTotal() * THREE_YEAR_FACTOR)))) { grades.addSevenScaleGrade(grade, getUnitValue(), getUnitWeight()); } gpaField.setText(grades.returnSevenScaleGPA() + " / 7.0"); wamField.setText("N / A"); displayCourseInfo(); } else { if ((!threeYearLimit) || (threeYearLimit && (grades.getUnitTotal() <= (getYearUnitTotal() * THREE_YEAR_FACTOR)))) { grades.addFourScaleGrade(grade, "australia", getUnitValue(), getUnitWeight()); } gpaField.setText(grades.returnFourScaleGPA() + " / 4.0"); wamField.setText("N / A"); displayCourseInfo(); } } else { if ((!threeYearLimit) || (threeYearLimit && (grades.getUnitTotal() <= (getYearUnitTotal() * THREE_YEAR_FACTOR)))) { grades.addFourScaleGrade(grade, "states", getUnitValue(), getUnitWeight()); } gpaField.setText(grades.returnFourScaleGPA() + " / 4.0"); wamField.setText("N / A"); displayCourseInfo(); } } } /** * Displays the course information. * ESCA-JAVA0076: */ private void displayCourseInfo() { display.append(Tools.returnSpace(4) + getCourseName() + Tools.returnNewline(2)); display.append(" Value : " + Tools.returnSpace(80) + Integer.toString(getUnitValue()) + Tools.returnNewline(1)); display.append(" Grade : " + Tools.returnSpace(80) + getCourseGrade() + Tools.returnNewline(1)); display.append(" Weight ++ " + Tools.returnSpace(78) + Integer.toString(getUnitWeight()) + Tools.returnNewline(1)); display.append(Tools.returnNewline(1)); } /** * Window resize event. */ private void includeResizeEvent() { this.addComponentListener ( new ComponentAdapter() { public void componentResized(ComponentEvent e) { appletDisplayHandler(); } } ); } /** * Controls the JApplet component visibility. * ESCA-JAVA0266: */ private void appletDisplayHandler() { final String ZOOM_WARNING = "It appears that web pages in your browser are zoomed out. \n\n" + "In order to display the applet, your browser needs to be set \n" + "at its default zoom level of 100% or greater. \n\n" + "Sorry about that."; if ((getWidth() < FRAME_SIZE_X) || (getHeight() < FRAME_SIZE_Y)) { contentPane.setVisible(false); if (!zoomWarningShown) { Message.showMessage(ZOOM_WARNING, "Browser zoom setting", "warning"); zoomWarningShown = true; } } else { contentPane.setVisible(true); } } /** * Adds the grades footer. * ESCA-JAVA0076: */ private void addGradesFooter() { constraints.insets = new Insets(10,0,0,0); constraints.ipadx = 0; constraints.ipady = 0; constraints.gridwidth = 1; constraints.weightx = 0; constraints.weighty = 0; constraints.gridx = 0; constraints.gridy = 2; contentPane.add(bottomPanel, constraints); } /** * Adds the place holders to the fields. */ private void addFieldPlaceholders() { courseName.setText("Course Name"); unitValue.setText("Unit Value"); courseGrade.setText("Course Grade"); courseWeight.setText("Course Weight"); } /** * Sets the course name. * @param value */ private void setCourseName(String value) {name = value;} /** * Returns the course name * @return */ private String getCourseName() {return name;} /** * Sets the unit value. * @param value */ private void setUnitValue(int value) {units = value;} /** * Returns the unit value. * @return */ private int getUnitValue() {return units;} /** * Sets the unit weight. * @param value */ private void setUnitWeight(int value) {weight = value;} /** * Returns the unit weight. * @return */ private int getUnitWeight() {return weight;} /** * Sets the course grade. * @param value */ private void setCourseGrade(String value) {grade = value;} /** * Returns the course grade. * @return */ private String getCourseGrade() {return grade;} /** * Sets the yearly unit total. * @param value */ private void setYearUnitTotal(int value) {yearUnitTotal = value;} /** * Returns the yearly unit total. * @return */ private int getYearUnitTotal() {return yearUnitTotal;} //***************************************** END PRIVATE METHODS *****************************************// //********************************************** START MAIN *********************************************// /** * Main * @param a */ public static void main(String[] a) { isApplication = true; isVisible = true; new GpaCalculatorGui(); } //*********************************************** END MAIN **********************************************// /** * ESCA-JAVA0007: */ public JFrame frame; private State state; private Validation valid; private JTextArea display; private String name, grade; private GpaCalculator grades; private Container contentPane; private JScrollPane scrollPane; private boolean zoomWarningShown; private GridBagConstraints constraints; private int units, weight, yearUnitTotal; private JButton nextButton, addButton, clearButton; private JCheckBox yesPercentageCheck, threeYearCheck; private JTextField unitsPerYear, courseName, unitValue, courseGrade, courseWeight, gpaField, wamField; private JPanel courseInfoPanel, bottomPanel, clearPanel, gradePanel, scaleTypePanel, leftPanel, rightPanel, scaleTypeContainer; private JLabel firstPrompt, secondPrompt, thirdPrompt, fourthPrompt, fifthPrompt; private JRadioButton australianLetterScale, americanLetterScale, fourScale, sevenScale; private boolean skip, usePercentageGrade, useAustralianLetterScale, useSevenScale, threeYearLimit; //********************************************** END CLASS **********************************************// }
/* COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved. This class calculates a university GPA and WAM. @site http://www.javaika.com @author Alexander Wait @version 2011-07-18 */ import java.text.DecimalFormat; public class GpaCalculator { /** * ESCA-JAVA0057: */ public GpaCalculator() {} //**************************************** START PUBLIC METHODS *****************************************// /** * Adds a grade. * @param percent * @param units * @param weight */ public void addSevenAcerPercentage(double percent, double units, double weight) { sumOfUnitTimesWeight += (units * weight); wamTotal += (percent * units * weight); for (int i = 0; i < sevenAcerPercentage.length; i ++) { if ((percent <= sevenAcerPercentage[i][0]) && (percent >= sevenAcerPercentage[i][1])) { sevenScoreTotal += (weight * units * sevenAcerScore[i]); break; } } sevenScaleGPA = (sevenScoreTotal / sumOfUnitTimesWeight); wam = wamTotal / sumOfUnitTimesWeight; } /** * Adds a grade. * @param grade * @param type * @param units * @param weight */ public void addFourScaleGrade(String grade, String type, double units, double weight) { sumOfUnitTimesWeight += (units * weight); if (type.equals("states")) { for (int i = 0; i < fourScaleGrade.length; i ++) { if (grade.equals(fourScaleGrade[i])) { fourScoreTotal += (weight * units * fourScaleBScore[i]); break; } } } if (type.equals("australia")) { for (int i = 0; i < sevenScaleGrade.length; i ++) { if (grade.equals(sevenScaleGrade[i])) { fourScoreTotal += (weight * units * fourScaleAScore[i]); break; } } } fourScaleGPA = (fourScoreTotal / sumOfUnitTimesWeight); } /** * Adds a grade. * @param grade * @param units * @param weight */ public void addSevenScaleGrade(String grade, double units, double weight) { sumOfUnitTimesWeight += (units * weight); for (int i = 0; i < sevenScaleGrade.length; i ++) { if (grade.equals(sevenScaleGrade[i])) { sevenScoreTotal += (weight * units * sevenScaleScore[i]); break; } } sevenScaleGPA = (sevenScoreTotal / sumOfUnitTimesWeight); } /** * Resets the variables. */ public void resetVariables() { sumOfUnitTimesWeight = 0; sevenScoreTotal = 0; fourScoreTotal = 0; sevenScaleGPA = 0; fourScaleGPA = 0; unitTotal = 0; wamTotal = 0; wam = 0; } /** * Increments the unit total. * @param value */ public void incrementUnitTotal(int value) { unitTotal += value; } /** * Returns the unit total. * @return */ public int getUnitTotal() { return unitTotal; } /** * Returns GPA on scale 1-4. * @return */ public String returnFourScaleGPA() { DecimalFormat places = new DecimalFormat("#.##"); return (Double.toString(Double.valueOf(places.format(fourScaleGPA)))); } /** * Returns GPA on scale 1-7. * @return */ public String returnSevenScaleGPA() { DecimalFormat places = new DecimalFormat("#.##"); return (Double.toString(Double.valueOf(places.format(sevenScaleGPA)))); } /** * Returns the WAM. * @return */ public String returnWAM() { DecimalFormat places = new DecimalFormat("#.##"); return (Double.toString(Double.valueOf(places.format(wam)))); } /** * Tests if grade supplied by user is valid. * @param grade * @param system * @return */ public boolean isValidLetterGrade(String grade, String system) { boolean validGrade = false; if (system.equals("states")) { for (String element : fourScaleGrade) { if (element.equals(grade)) { validGrade = true; } } } if (system.equals("australia")) { for (String element : sevenScaleGrade) { if (element.equals(grade)) { validGrade = true; } } } return validGrade; } //***************************************** END PUBLIC METHODS ******************************************// private int sumOfUnitTimesWeight, unitTotal; private static final String[] sevenScaleGrade = {"HD", "D", "C", "P", "CP", "F"}; private static final double[] sevenScaleScore = {7.00, 6.00, 5.00, 4.00, 3.00, 0.00}; private static final double[] fourScaleAScore = {4.00, 3.00, 2.00, 1.00, 0.50, 0.00}; private static final double[] sevenAcerScore = {7.00, 6.50, 6.00, 5.50, 5.00, 4.50, 4.00, 3.00, 0.00}; private static final String[] fourScaleGrade = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"}; private static final double[] fourScaleBScore = {4.00, 4.00, 3.67, 3.33, 3.00, 2.67, 2.33, 2.00, 1.67, 1.33, 1.00, 0.67, 0.00}; private static final double[][] sevenAcerPercentage = {{100,80}, {79,75}, {74,70}, {69,65}, {64,60}, {59,55}, {54,50}, {49,45}, {44,0}}; private double sevenScoreTotal, fourScoreTotal, sevenScaleGPA, fourScaleGPA, wam, wamTotal; //********************************************** END CLASS **********************************************// }
/* COPYRIGHT (C) 2010 -2013 by Alexander Wait. All Rights Reserved. This class defines colors and color methods. @site http://www.javaika.com @author Alexander Wait @version 2012-05-18 */ public class ColorFunctions { private static final int HEXADECIMAL_BASE = 16; private static final int COLOR_COMPONENT_RED = 250; private static final int COLOR_COMPONENT_GREEN = 250; private static final int COLOR_COMPONENT_BLUE = 250; private ColorFunctions() {} //**************************************** START PUBLIC METHODS *****************************************// /** * Returns the color in hexadecimal format. * @param sliderValue * @return */ public static String returnHexadecimalColor(int sliderValue) { String compFirst = ""; String compSecond = ""; int counter = -1; for (int i = 0; i < HEXADECIMAL_BASE; i ++) { compFirst = returnComponent(i); for (int j = 0; j < HEXADECIMAL_BASE; j ++) { compSecond = returnComponent(j); counter ++; if (counter == sliderValue) { break; } } if (counter == sliderValue) { break; } } return ( "#" + compFirst + compSecond + compFirst + compSecond + compFirst + compSecond ); } /** * Return the set red color component * for setting the programs background color. * @return */ public static int red() { return COLOR_COMPONENT_RED; } /** * Return the set green color component * for setting the programs background color. * @return */ public static int green() { return COLOR_COMPONENT_GREEN; } /** * Return the set blue color component * for setting the programs background color. * @return */ public static int blue() { return COLOR_COMPONENT_BLUE; } //***************************************** END PUBLIC METHODS ******************************************// //**************************************** START PRIVATE METHODS ****************************************// /** * Returns the hexadecimal component. * ESCA-JAVA0076: * @param index * @return */ private static String returnComponent(int index) { String component = ""; switch (index) { case 10: component = "A"; break; case 11: component = "B"; break; case 12: component = "C"; break; case 13: component = "D"; break; case 14: component = "E"; break; case 15: component = "F"; break; default: component = Integer.toString(index); break; } return component; } //***************************************** END PRIVATE METHODS *****************************************// //********************************************** END CLASS **********************************************// }
/* COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved. This class returns the domain attributes. @site http://www.javaika.com @author Alexander Wait @version 2012-07-06 */ public class Domain { private static final String DOMAIN = "javaika.com"; private static final boolean RUN_LOCAL = false; private static final boolean prefix = true; private static final String PORT = "80"; private Domain() {} //**************************************** START PUBLIC METHODS *****************************************// /** * Returns the domain name. * @return */ public static final String getDomain() { if (prefix) { return ("www." + DOMAIN); } else { return (DOMAIN); } } /** * Returns the port number. * @return */ public static final String getPort() { if (RUN_LOCAL) { return (":" + PORT); } else {return ("");} } //***************************************** END PUBLIC METHODS ******************************************// //********************************************** END CLASS **********************************************// }
/* COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved. This class displays message dialogs. @site http://www.javaika.com @author Alexander Wait @version 2011-07-18 */ import javax.swing.*; public class Message { private Message(){} //**************************************** START PUBLIC METHODS *****************************************// /** * Displays a message dialog. * @param text * @param heading * @param type */ public static void showMessage(String text, String heading, String type) { new JOptionPane(); Object[] options = {}; if (type.equals("error")) { JOptionPane.showOptionDialog(null, text, heading, JOptionPane.YES_OPTION, JOptionPane.ERROR_MESSAGE, null, options, null); } if (type.equals("information")) { JOptionPane.showOptionDialog(null, text, heading, JOptionPane.YES_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, null); } if (type.equals("warning")) { JOptionPane.showOptionDialog(null, text, heading, JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE, null, options, null); } if (type.equals("question")) { JOptionPane.showOptionDialog(null, text, heading, JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, null); } } //***************************************** END PUBLIC METHODS ******************************************// //********************************************** END CLASS **********************************************// }
/* COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved. This class provides handy tools. @site http://www.javaika.com @author Alexander Wait @version 2012-02-01 */ public class Tools { private static final int EXCEPTION_LINE_BEAK = 2; private Tools() {} //**************************************** START PUBLIC METHODS *****************************************// /** * This method returns the line number and path where it's called. * The syntax new Exception().getStackTrace()[0].getLineNumber() * will only give the current line number of the source file. * @return */ public static String thisPathAndLine() { String lineAndPath = ""; String stackTrace = ""; stackTrace = new Exception().getStackTrace()[1].toString(); for (int i = stackTrace.length()-1; i >= 0; i --) { if (stackTrace.charAt(i) == ')') {continue;} else if (stackTrace.charAt(i) == '(') {break;} else {lineAndPath = (stackTrace.charAt(i) + lineAndPath);} } return lineAndPath + returnNewline(EXCEPTION_LINE_BEAK); } /** * Delays execution. * @param length */ public static void delay(long length) { for (long i = 0; i < length; i ++) {} } /** * This method returns a space. * @param length * @return */ public static String returnSpace(int length) { String space = ""; for (int i = 0; i < length; i ++) { space += " "; } return space; } /** * Assigns newlines to a string. * @param lines * @return */ public static String returnNewline(int lines) { String newline = ""; for (int i = 0; i < lines; i++) { newline += "\n"; } return newline; } /** * Returns the users desktop path. * @return */ public static String returnDesktopPath() { return (System.getProperty("user.home") + "/Desktop").replace("\\", "/") + "/"; } //***************************************** END PUBLIC METHODS ******************************************// //********************************************** END CLASS **********************************************// }
/* COPYRIGHT (C) 2010 - 2013 by Alexander Wait. All Rights Reserved. This class is used for sophisticated validation of data. @site http://www.javaika.com @author Alexander Wait @version 2010-07-18 */ import java.util.regex.Pattern; public class Validation { //************************************** START INITIALISATION CODE **************************************// private static final String IP_ADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; private static final String NUMBER_PATTERN = "[+-]?[0-9]*[.]?[0-9]*"; private static final String ALPHANUMERIC_PATTERN = "[A-Za-z0-9]*"; private static final String LETTER_PATTERN = "[A-Za-z]*"; private static final String INTEGER_PATTERN = "[0-9]*"; /** * Validation constructor. */ public Validation() { count = 0; } //*************************************** END INITIALISATION CODE ***************************************// //**************************************** START PUBLIC METHODS *****************************************// /** * Tests a string against a supplied mask string. * The key for testing a string is as follows. * '^' represents a upper case letter. * '#' represents a lower case letter. * '?' represents a digit. * @param maskString * @param testString * @return result() */ public boolean maskValidation(String maskString, String testString) { count = 0; if (maskString.length() == testString.length()) { for (int i = 0; i < maskString.length(); i ++) { if (maskString.charAt(i) == testString.charAt(i)) { count ++; } if (maskString.charAt(i) == '?') { for (char element : digit) { if (testString.charAt(i) == element) { count ++; } } } if (maskString.charAt(i) == '#') { for (char element : lowerCase) { if (testString.charAt(i) == element) { count ++; } } } if (maskString.charAt(i) == '^') { for (char element : upperCase) { if (testString.charAt(i) == element) { count ++; } } } } } if (count != testString.length()) {return false;} else {return true;} } /** * Checks the validation of an IP address. * @param testString * @return */ public boolean ipAddressValidation(String testString) { pattern = Pattern.compile(IP_ADDRESS_PATTERN); return (pattern.matcher(testString).matches()); } /** * Checks the validation of an integer. * @param testString * @return */ public boolean integerValidation(String testString) { pattern = Pattern.compile(INTEGER_PATTERN); return (pattern.matcher(testString).matches()); } /** * Checks the validation of a letter string. * @param testString * @return */ public boolean letterValidation(String testString) { pattern = Pattern.compile(LETTER_PATTERN); return (pattern.matcher(testString).matches()); } /** * Checks the validation of an alphanumeric string. * @param testString * @return */ public boolean alphanumericValidation(String testString) { pattern = Pattern.compile(ALPHANUMERIC_PATTERN); return (pattern.matcher(testString).matches()); } /** * Checks the validation of an alphanumeric string. * @param testString * @return */ public boolean numberValidation(String testString) { pattern = Pattern.compile(NUMBER_PATTERN); return (pattern.matcher(testString).matches()); } //***************************************** END PUBLIC METHODS ******************************************// private int count; private Pattern pattern; /** * ESCA-JAVA0007: */ public static String[] numberOperator = {"PI", "e"}; /** * ESCA-JAVA0007: */ public static char[] digit = {'0','1','2','3','4','5','6','7','8','9'}; /** * ESCA-JAVA0007: */ public static char[] simpleOperator = {'-', '+', 'v', '^', '/', 'x', '*', ','}; /** * ESCA-JAVA0007: */ public static char[] number = {'-','+','.','0','1','2','3','4','5','6','7','8','9','E','I','n','f','i','t','y'}; /** * ESCA-JAVA0007: */ public static String[] singleOperator = {"Sin", "Cos", "Tan", "Fac", "Inv", "Abs"}; /** * ESCA-JAVA0007: */ public static String[] doubleOperator = {"Log", "Mod", "Pwr", "Pnr", "Cwr", "Cnr"}; /** * ESCA-JAVA0007: */ public static char[] lowerCase = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z'}; /** * ESCA-JAVA0007: */ public static char[] upperCase = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P','Q','R','S','T','U','V','W','X','Y','Z'}; //********************************************** END CLASS **********************************************// }