Widgets and Events: Now see the Magic/h2>

Making Widgets Live

If you have ventured here in the Swing Era or the pre-Java8 era, you got to see anonymous nested inner classes with all fo their ugly boilerplate. Ever been treated to this heinous sight?

JButton b = new JButton("Click me now!!");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
        //actual code that does work
});     // That's "Sad Santa."

And the import police demanded this.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

Things are svelter and sleeker now, but this means that there is some "magic" that will require real explanation. So, strap on your seatbelts, and go for an exciting ride. Then learn how you got there.

So to get started, copy Widget.java to a file named LiveWidget.java. Update it so it compiles.

Now add these two lines of code to your start method.

putText.setOnAction( e -> tf.setText("Hey look at me!"));
quitButton.setOnAction( e -> Platform.exit());

Compile and run. Click on the button that says, "Put Text" and text will appear in the text field. Click on the quit button and watch the app quit.

Now modify the stop method like so.

    public void stop()
        System.out.println("I quit politely");

Recompile and run again. This time when you hit the quit button, you wil see that stop got called. Change Platorm.exit() to System.exit() and experience chagrin.

Now we must understand why this works.