CS 252

Lab #7


  1. In the Scala interpreter, run this code:
    import java.awt._
    import java.awt.event._
    import javax.swing._
    
    // This makes an implicit conversion from a function to an action listener
    // We wouldn't need this if the Java API was functional
    implicit def makeAction(action : (ActionEvent)=>Unit) = new ActionListener {
        override def actionPerformed(event: ActionEvent) { action(event) } 
      }
    
    val frame = new JFrame
      
    val textArea = new JTextArea(20, 50)
    val button1 = new JButton("Hello")
    val button2 = new JButton("Exit")
    var count = 0
      
    button1.addActionListener((e : ActionEvent) => { count += 1; textArea.append("Hello " + count + "\n") })  
      
    val panel = new JPanel    
    panel.add(button1)
    panel.add(button2)  
    frame.add(panel, BorderLayout.NORTH)
    frame.add(textArea)
    frame.pack()
    frame.setVisible(true)

    Now click the Hello button a few times. What happens? Why?

  2. Click the Exit button. What happens? Why?
  3. Fix the Exit button so that it exits the program. (System.exit(0))

    Translate the code to Java:

    public class Lab7 {
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            ...
            frame.setVisible(true);
        }
    }

    What is your program?

  4. Compile and run the program. How many .class files were generated? What are they called?
  5. Run javap Lab7, then run javap on all other class files. What is the output?

    Note: In bash, you need to escape $ in file names with a \

  6. What happened to the final local variables in Lab7.main?
  7. Explain the constructors for the inner classes.