20-CS-694 Advanced Programming Techniques Spring 2012
Hints for Homework Assignment 1

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

Java Warm Up

Due: April 5, 2012 (submit instructions: here)

JButtons:
    Use an array of JButtons for the squares. They may be declared like this:
  JButton cells[][] = new JButton[3][3];
Attach an ActionListener to each JButton like this:
  JPanel p = new JPanel();
  p.setLayout(new GridLayout(3,3));
  for (int i=0 ; i < 3 ; i++) {
     for (int j=0 ; j < 3 ; j++) {
        p.add(cells[i][j] = new JButton(""));
        cells[i][j].addActionListener(this);
     }
  }					
But be sure to implement the ActionListener interface like this:
  public void actionPerformed (ActionEvent evt) {
     for (int i=0 ; i < 3 ; i++) {
        for (int j=0 ; j < 3 ; j++) {
           if (evt.getSource() == cells[i][j]) {
              cells[i][j].setText(mark);
              cells[i][j].removeActionListener(this);
              ...
           }
        }
     }
     ...
  }
where mark is a String of value X or O, setText(mark) puts the appropriate label in the clicked square, removeActionListener makes it so the label cannot be changed, and ... indicates other statements should be placed at those points.
 
Constraints:
Some constraints have to be added. For example, to check whether a column is all of one mark you might use a function like this:
  public boolean checkColumn (int c, String mark) {
     for (int i=0 ; i < 3 ; i++)
        if (!cells[i][c].getText().equals(mark)) return false;
     return true;
  }
which returns true if and only if a column has all X or all O labels.
      
 
Sound:
A soundbite from a remote computer may be used when someone wins. The name of the soundbite file is excellnt.au and it is located at location http://gauss.ececs.uc.edu/Courses/c694/homework/. Code for playing sound might look like this:
  String loc = 
     "http://gauss.ececs.uc.edu/Courses/c694/homework/excellnt.au";
  try { play(new URL(loc)); } catch (Exception e) { }
this code must be run from the Applet class, not the JFrame class.