GUI – Refinements – Error Messages

  1. Zeller Pascal
  2. Zeller Java
  3. validDate Revisited – Python
  4. validDate Revisited – Java
  5. Java GUI
  6. GUI – Refinements – ComboBoxes
  7. GUI – Refinements – Error Messages
  8. GUI Refinements – Focus
  9. GUI Refinements – Today

The next refinement is simple. I want the output box to change colour, when the output of the calculation contains the word ‘Error’. How I have decided to handle this is by creating a new String before sending setting it as the content of the JTextField element. I have also decided to add a few more error messages, one each for the three inputs. If the output string contains the word ‘Error’ then the background of the JTextField is changed to Red otherwise it checks to see if the background colour is Red and switches it back to being Black.

public void actionPerformed(ActionEvent evt) {
        Calc calc = new Calc();
        int inputDay;
        int inputMonth;
        int inputYear;
        String output = null;
        if (comboBoxDay.getSelectedIndex() == 0)
        {
            output = "Error: select a valid day";
        }else if(comboBoxMonth.getSelectedIndex() == 0){
            output = "Error: select a valid month";
        }else if(textFieldYear.getText().equals("")){
            output = "Error: enter a valid year";
        }else{
            inputDay = comboBoxDay.getSelectedIndex();
            inputMonth = comboBoxMonth.getSelectedIndex();
            inputYear = Integer.parseInt(textFieldYear.getText());
            output = calc.Calculate(inputDay, inputMonth, inputYear);
        }
        
        if (output.contains("Error")){
            labelOutput.setBackground(Color.RED);
        }else{
            if (labelOutput.getBackground() == Color.RED){
                labelOutput.setBackground(Color.BLACK);
            }
        }
        
        labelOutput.setText(output);
    }

The code results in the following effect on detecting an Error.

GUI after detecting an Error.