/* ================================================================ *
 *  PressMe.java - A simple GUI using a button and a drawing panel  *
 *                                                                  *
 *  Author: Bary W Pollack                                          *
 *  Date:   March 1, 2008                                           *
 * ================================================================ */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PressMe extends JFrame {
    private Color[] color       = { Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW,
                                    Color.CYAN, Color.MAGENTA, Color.BLACK, Color.GRAY, 
                                    Color.WHITE };
    private String[] name       = { "RED", "GREEN", "BLUE", "YELLOW",
                                    "CYAN", "MAGENTA", "BLACK", "GRAY", "WHITE" };
    private JPanel outerPanel   = new JPanel();
    private JPanel jpColorPanel = new ColorPanel();
    private JLabel jlName       = new JLabel(name[0]);
    private JButton jbPressMe   = new JButton("  Press Me !  ");
    private int nIndex          = 0;

    public PressMe() {
        super(">>> Simple GUI in Java <<<");
        outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
        JPanel jp;

        jp = new JPanel();
        jp.add(jbPressMe);
        jbPressMe.addActionListener(new ButtonHandler());
        outerPanel.add(jp);

        jp = new JPanel();
        jp.add(new JLabel("Java color: "));
        jp.add(jlName);
        outerPanel.add(jp);

        jp = new JPanel();
        jp.add(jpColorPanel);
        outerPanel.add(jp);

        setContentPane(outerPanel);
        setDefaultCloseOperation(EXIT_ON_CLOSE); 
        setSize(280, 160);
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true); 
    }

    private class ButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            nIndex = ++nIndex % color.length;
            jlName.setText(name[nIndex]);
            jpColorPanel.repaint();
            Toolkit.getDefaultToolkit().beep();
        }
    }

    class ColorPanel extends JPanel {

        public Dimension getPreferredSize() {
            return new Dimension(150, 50); 
        } 

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(color[nIndex]);
            g.fillRect(0, 0, 150, 50);
            g.setColor(Color.BLACK);
            g.drawRect(0, 0, 149, 49);
            g.setColor(Color.WHITE);
            g.drawRect(1, 1, 147, 47);
        }

    }

    public static void main(String[] args) {
        new PressMe();
    }

}
