/*
 * File: SimpleTableDemo.java
 * --------------------------
 * This program expands the SimpleTableExample code to
 * allow the user to change the number of columns and to
 * add new buttons.
 */

import acm.gui.*;
import acm.program.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * This class arranges six buttons in a table.
 */
public class SimpleTableDemo extends Program implements ActionListener {

/** Set the program dimensions */
	public static final int APPLICATION_WIDTH = 300;
	public static final int APPLICATION_HEIGHT = 200;

/** Initialize the display */
	public void init() {
		setLayout(new TableLayout(0, 3));
		layoutManager = (TableLayout) getLayout();
		columnField = new IntField(3, 1, 6);
		columnField.addActionListener(this);
		addButton = new JButton("Add");
		addButton.addActionListener(this);
		add(addButton, SOUTH);
		deleteButton = new JButton("Delete");
		deleteButton.addActionListener(this);
		deleteButton.setEnabled(false);
		add(deleteButton, SOUTH);
		add(new JLabel(" Columns:"), SOUTH);
		add(columnField, SOUTH);
		for (int i = 0; i < 6; i++) {
			addButton();
		}
	}

/** Action listener */
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if (source == columnField) {
			layoutManager.setColumnCount(columnField.getValue());
			validate();
		} else if (source == addButton) {
			addButton();
			layoutManager.setColumnCount(columnField.getValue());
			validate();
		} else if (source == deleteButton) {
			remove(selectedButton);
			selectedButton = null;
			deleteButton.setEnabled(false);
			layoutManager.setColumnCount(columnField.getValue());
			validate();
		} else {
			if (selectedButton != null) {
				selectedButton.setBackground(oldBackground);
			}
			selectedButton = (JButton) source;
			oldBackground = new Color(selectedButton.getBackground().getRGB());
			selectedButton.setBackground(SELECTED_BACKGROUND_COLOR);
			deleteButton.setEnabled(true);
		}
	}

/* Add the next button to the layout */
	private void addButton() {
		JButton button = new JButton("" + (char) ('A' + nextButtonIndex % 26));
		button.addActionListener(this);
		add(button);
		nextButtonIndex++;
	}

/* Color to use for selected button */
	private static final Color SELECTED_BACKGROUND_COLOR = new Color(0xFF99FF);

/* Private instance variables */

	private TableLayout layoutManager;
	private JButton addButton;
	private JButton deleteButton;
	private JButton selectedButton;
	private Color oldBackground;
	private IntField columnField;
	private int nextButtonIndex;

/* Standard Java entry point */
/* This method can be eliminated in most Java environments */
	public static void main(String[] args) {
		new SimpleTableDemo().start(args);
	}
}
