
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class GuiThread 
{
    private static final int DELAY = 1000;  // one second
    private static JTextField textField;

    public static void main(String[] args) 
    {
        JFrame frame = new JFrame();

        final int FIELD_WIDTH = 20;
        textField = new JTextField(FIELD_WIDTH);
        textField.setText("Click a button!");

        JButton helloButton = new JButton("Say Hello");
        helloButton.addActionListener(
            createGreetingButtonListener("Hello, World!"));

        JButton goodbyeButton = new JButton("Say Goodbye");
        goodbyeButton.addActionListener(
            createGreetingButtonListener("Goodbye, World!"));

        frame.setLayout(new FlowLayout());

        frame.add(helloButton);
        frame.add(goodbyeButton);
        frame.add(textField);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

        for (int i = 1; i <= 20; i++) {
            print("Main program here!");
            try {
                Thread.sleep(DELAY);
            } 
            catch (InterruptedException ex) {
                print("Done!");
            }
        }
    }

    private static void print(String message) 
    {
        String threadName = Thread.currentThread().getName();
        System.out.println("Thread " + threadName
                           + ": " + message);
    }

    public static ActionListener 
        createGreetingButtonListener(final String message) 
    {
        return new 
            ActionListener() 
            {
                public void actionPerformed(ActionEvent event) 
                {
                    textField.setText(message);
                    print(message);
                }
            };
    }
}
