Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

Arrays of Objects

A simple example using an array of TextFields and Labels.

We re-visit the Applet to calculate resort temperatures set as a problem earlier on ( repetiton page ).

Here the Labels hold the days and the TextFields are used to input the temperatures for each day.

A Panel is used with a Grid Layout in 7 rows and two columns.

 

 

 

 

 

 

 

 

 

 

 

 

The use of libraries such as awt is a mastery aspect at SL.

The use of arrays is a mastery aspect at SL.

 

 

 

 

 

 

 

Font name, style and size

 

 

setBackground can be applied to most awt components.

Most constants in the Color class are easily guessed.

 

All text components can have fonts, foreground(font) colors and background colours set.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

neat eh?

sometimes I amaze myself!

 

 

 

 

 

 

Standard algorithm for summing numbers.

 

 

 

 

We also use this Applet to show some aspects of using Fonts, Colours and alignment of text.

The Applet uses an array of Strings which is filled with data rather than declared as a fixed size. Any array can be initialised with values in this way:

      int[] arrayOfInt = new int[] {0, 2, 4, 7, 8, 9};

This automatically creates an arrray of sufficient size to hold the specified values.


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/**
* Applet to get 7 temperatures and calculate the average
* This version uses arreays of TextFields and Labels
* It also demonstrates some aspects of colour and layout.
* @author Mr J
* @version 20040901, 65 years since the invasion of Poland and the start of ww2
*/

public class TemperatureArray extends Applet implements ActionListener
{
   // A static final is a constant value throughout the Applet
   static final int DAYS = 7;
   // Labels for each day
   private String[] days = new String[] { "Monday:", "Tuesday:", "Wednesday:",
                                          "Thursday", "Friday: ", "Saturday:",
                                          "Sunday" };
   // arrays of text fields and labels for the temperatures
   private TextField[] boxes = new TextField[DAYS];
   private Label[] labels = new Label[DAYS];
   // button and results objects
   private Button pressMe = new Button("Average");
   private Label greeting = new Label("Average will be shown here");
   private Font myFont = new Font("Courier", Font.BOLD, 10);
  /**
   * Add objects to the Applet  
   */

   public void init()
   {
     // Set Applet background
     setBackground(Color.CYAN);
     // The panel is used for neat layout
     Panel weekPanel = new Panel();
     weekPanel.setLayout(new GridLayout(7, 2));
     // add labels and boxes to Panel  
     for (int x = 0; x < DAYS; x++)
     {
       // create Label with right alignment
       labels[x] = new Label(days[x], Label.RIGHT);
       labels[x].setFont(myFont);          // set Label font
       boxes[x] = new TextField(5);        // create TextField
       boxes[x].setFont(myFont);           // set font here too
       weekPanel.add(labels[x]);           // add Labels, TextFields to Panel
       weekPanel.add(boxes[x]);
     }
     // add Panel and remaining objects
     add(weekPanel);
     add(pressMe);
     add(greeting);
     // Causes button presses to be detected
     pressMe.addActionListener(this);
   }
  /**
   * Carried out when pressMe is pressed
   *
   * @param e carries details about the event that occurred
   */

   public void actionPerformed(ActionEvent e)
   {
     // Check for empty boxes (helper method)
     int empty = numBoxesNotFilled();

     if (empty > 0) // There are some empty boxes
     {
       greeting.setText("Please fill the " + empty + " red boxes");
     }
     else // All boxes filled, do calculation
     {
       greeting.setText("Average: " + calcAverage());
     }
   }
   /**
   * This method checks for unfilled boxes and turns them RED
   *
   * @return number of unfilled text boxes
   */

   private int numBoxesNotFilled()
   {
     int empties = 0; // used to count empty boxes

     for(int x = 0; x < DAYS; x++)          // for each day
     {
       if (boxes[x].getText().equals(""))   // if empty
       {
         empties++; // count this one
         boxes[x].setBackground(Color.RED); // make it red
       }
       else // if it was red, turn it back
       {
         boxes[x].setBackground(Color.WHITE);
       }
     }
     return empties;
   }
   /**
   * This method sums the boxes and returns the average
   *
   * @return average temperature from boxes
   */

   private double calcAverage()    
   {
     double sum = 0.0;
     for (int x = 0; x < DAYS; x++)
     {
       sum = sum + Double.parseDouble(boxes[x].getText());
     }
     return (sum / 7.0);
   }
}

 

Related: [ Java home | Previous: Arrays | Next: Array Operations ]

Examples using 2D arrays of objects are on the next page.


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand;
This page was last modified: May 31, 2009