IC211 Spring AY 2020

HW GUIs

Name (Last, First): ____________________________________________________ Alpha: _____________________
Describe help received: _________________________________________________________________

Ex20.java CBn.java
import javax.swing.*;

public class Ex20 {
  public static void main(String[] args) {
    HW20Frame F = new HW20Frame();

    F.setVisible(true);
  }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CBn extends JButton implements ActionListener {
  private int count = 0;
  public CBn(String label) {
    super(label);
    this.addActionListener(this);
  }

  public void actionPerformed(ActionEvent e) {
    count++;
  }
}
HW20Frame.java
import javax.swing.*;
import java.awt.*;

public class HW20Frame extends JFrame {
  public HW20Frame() {
    CBn b = new CBn("click me");

    add(b, BorderLayout.NORTH);
    pack();
  }
}

Notice that in this little program there is something kind of cool: the CBn class is a button that is its own action listener. Nice, right? So the line

this.addActionListener(this);
is basically saying "I am my own ActionListener".

  1. [15pts] Instead of writing HW20Frame F = new HW20Frame(); for the first line of main, suppose I had written:
    JFrame F = new HW20Frame();
    Would the result be: compile-time error, run-time error, or OK? Why? Explain your answer thoroughly!
  2. [15pts] Compile and run the above program. You'll notice that clicking the x at the top of the window does not exit the program. I'd like to change things so that clicking on the x closes the program, but before doing so prints the number of button clicks on the screen, like this:
    Button clicked 3 times.
    The nicest way to do this is to make the CBn class listen not only for button clicks, but also for window closing events!

    When we define a class that listens for window events, we must either implement the WindowListener interface or extend the WindowAdapter class. (see the previous lesson's notes) Extending the class is certainly easier. Explain why, however, if we want to modify our CBn class so that it not only serves as a button and listens for button clicks, but also listens for window events, we cannot extend WindowAdapter. Instead, we must implement WindowListener.



  3. [70pts] Actually modify the Ex20 program as described in the previous problem: i.e. when the user clicks on the x in the window, the program exits, but before exiting it prints the number of times the button has been clicked out on the screen.



Turn in: this sheet, the codeprint of your source code, and screen captures of both your GUI and the terminal window showing the output when your GUI window is closed.
Don't forget to add proper Javadoc formatted comments in the source code! Note: You do NOT have to write Javadoc comments for empty block methods that exist only to satisfy implementation requirements for interfaces.