// Allison Obourn
// CS& 141, Winter 2021
// Lecture 18

// An object template class that creates a GUI when constructed. This GUI
// allows contains 10 textboxes and 10 buttons. They are displayed in columns
// with one textbox and one button per row. When a button is clicked the 
// word hello appears in the textbox next to it.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CounterGUI {
   // an array of our textboxes with the top textbox added first
   private JTextField[] texts;

   public CounterGUI() {
      JFrame window = new JFrame();
      window.setLayout(new GridLayout(10, 1));
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
      // create each textbox, button pair and add the textbox to the array
      texts = new JTextField[10];
      for(int i = 0; i < 10; i++) {
         texts[i] = addRow(window, i + 1);
      }
      
      window.pack();
      window.setVisible(true);
   }
   
   // Creates a panel with a textbox and button on it side by side. 
   // Adds this to the passed in window. The button text displays
   // the passed in number and the texbox is returned
   private JTextField addRow(JFrame window, int num) {
      JPanel panel = new JPanel(new FlowLayout());
      JTextField text = new JTextField(10);
      panel.add(text);
      
      JButton button = new JButton("" + num);
      panel.add(button);
      
      MyActionListener action = new MyActionListener();
      button.addActionListener(action);
      
      window.add(panel);
      return text;
   }
   
   // Adds the word hello to the textbox next to the button that
   // was clicked.
   private class MyActionListener implements ActionListener {
       public void actionPerformed(ActionEvent event){

           int button = Integer.parseInt(event.getActionCommand());
           texts[button - 1].setText("hello");


       }
   }


}