/*
   Chapter 5:  5.3
   Programmer: Brad Shedd
   Date:    June 9, 2006
   Filename:   Checkerboard.java
   Purpose: This program will demonstrate arrays and looping structures.
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;

public class Checkerboard extends Frame implements ActionListener
{
   Panel checkPanel =
new Panel();
      TextArea checkDisplay[] =
new TextArea[16];

   Panel inputPanel =
new Panel();
      Label startLabel =
new Label("Start");
      TextField startField =
new TextField(3);
      Label stopLabel =
new Label("Stop");
      TextField stopField =
new TextField(3);
      Label stepLabel =
new Label("Step");
      TextField stepField =
new TextField(3);
      Button goButton =
new Button("Go");

  
int start, stop, step, i;

  
public Checkerboard()
   {
     
int start = 0, stop = 0, step = 0;

     
this.setLayout(new BorderLayout());
         checkPanel.setLayout(
new GridLayout(4,4,2,3));
         inputPanel.setLayout(
new FlowLayout());

     
//loop
      for (int i = 0; i < 16; i++)
      {

         checkDisplay[i] =
new TextArea(null,3,5,3);
        
if (i < 17)
            checkDisplay[i].setText(
"" + i);
        
else
            checkDisplay[i].setText("" + i);
         checkDisplay[i].setEditable(
false);
         checkDisplay[i].setBackground(Color.white);
         checkPanel.add(checkDisplay[i]);
      }

     
// add components to input panel
      inputPanel.add(startLabel);
      inputPanel.add(startField);
      inputPanel.add(stopLabel);
      inputPanel.add(stopField);
      inputPanel.add(stepLabel);
      inputPanel.add(stepField);
      inputPanel.add(goButton);

     
// add panels
      add(inputPanel, BorderLayout.CENTER);
      add(checkPanel, BorderLayout.NORTH);

      goButton.addActionListener(
this);
   }
// end public Checkerboard

   public static void main(String[] args)
   {
      Checkerboard f =
new Checkerboard();
      f.setBounds(50,100,300,375);
      f.setTitle(
"Checkerboard");
      f.setVisible(
true);
   }
//end main

      public void actionPerformed(ActionEvent e)
      {
            start = Integer.parseInt(startField.getText());
            stop = Integer.parseInt(stopField.getText());
            step = Integer.parseInt(stepField.getText());

           
for (i = 0; i < checkDisplay.length; i++)
            {
               checkDisplay[i].setBackground(Color.red);
            }
           
for (i = start; i <= stop; i += step)
            {
               checkDisplay[i].setBackground(Color.green);
            }
           
if (start > 15 || stop > 15 || step > 15)
            {
               JOptionPane.showMessageDialog(
null, "Enter a number between 0 and 15","Error", JOptionPane.ERROR_MESSAGE);
            }

      }
//end actionPerformed

} //end Checkerboard

Homepage