//
// Translated into Scala from the jython version seen at
//   http://www.eros-os.org/pipermail/e-lang/2002-April/006351.html ,
// which just happened to be a simple example at the top of
// the Google heap for "jython swing simple".
//

import javax.swing.{ JButton => JSwJB };

class sbwob extends javax.swing.JFrame {

    var exitButton : JSwJB = _;
    var paintCalls = 0;
    var buttonPresses = 0;

    override def paint (g: java.awt.Graphics) = {

        paintCalls = paintCalls + 1;

        Console.println( "sbwob paint calls " + this.paintCalls );
        g.setColor(java.awt.Color.black);
        g.drawString("hello", 10, 10);
        g.fillOval(10, 10, 100, 100);
    }

    def mkExitButton = exitButton = new JSwJB( "Get me Out" );

    def init = {
        Console.println( "sbwob frame thing" );
        this.setTitle( "sbwob frame thing" );
        this.setSize(256, 256);
        mkExitButton;
        exitButton.addActionListener(goAway());

        this.getContentPane().add( exitButton );
    }

    // Inner class to handle button presses
    //   Will exit only after 6 or more repaints.
    case class goAway with java.awt.event.ActionListener {

        def actionPerformed ( e: java.awt.event.ActionEvent ) = {
            buttonPresses = buttonPresses + 1;

            if( sbwob.this.paintCalls > 5 ) {
                Console.println( "Button pressed " +
                    sbwob.this.buttonPresses + " times.  Exiting." );
                System.exit(0);
            }
        }
    }
}

object sbw_main {

    def main ( args : Array[String] ) = {

        var myhr = new sbwob;
        myhr.init;
        myhr.setVisible(true);

        Thread.sleep(20000);
        /*
        catch {
            // How can I catch just the InterruptedException?
            case Throwable =>
                Console.println( "20-second sleep interrupted." );
        }
        */

        var m: String =
            if( myhr.buttonPresses == 0 ) "No button pressed.";
            else   "Button pressed " + myhr.buttonPresses + " times.  Exiting.";

        Console.println( m + "  Ran out of patience." );
        System.exit( 0 );
    }
}

