I am trying to read a textfield. I am using the string=textfield.getText() notion, but all I get a is a blank string back. I am using netbeans and I am using the gui designer within it. I want to hit the "create grid" button and have it create a grid from the integers that the user inputs into the textfield. I have a listener on the button, but I do not know what listener (if any) to put on the the JTextField.

Here is some of the code. Any help would be greatly appreciated.
First the GUI code

//This is the action listener for the button
private void   CreateNewGridButtonActionPerformed (java.awt.event.ActionEvent evt)
 {                                                    
        CookieMonster cookie =new CookieMonster();//CookieMonster is my main class
        numberOfRows=numberOfRowsField.getText();
        numberOfColumns=numberOfColumnsField.getText();
        System.out.println(numberOfRows);
}                                                   
//this is my best guess of a listener for the JTextfield
    private void numberOfRowsFieldActionPerformed(java.awt.event.ActionEvent evt) {                                                  
                    numberOfRows=numberOfRowsField.getText();
    }                                                 

it will always return an empty string.

Again any help is appreciated. My code in its entirety is attached in files

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Attachments
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myfirstcookie;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;


public class CookieMonster extends FirstWindow {

    public static JTextField columnTextField=new JTextField();
    public static JTextField rowTextField=new JTextField();
    public static JButton clearGrid=new JButton("Clear Grid");
    public static JButton createGrid=new JButton("Create Grid");
    public static JButton placeBlocks=new JButton("Place Block");
    public static int numberOfRows=10;
    public static int numberOfColumns=10;
    public static Grid obstacleCourse;
    public static GraphicGrid showGrid;
    public FirstWindow commandConsole=new FirstWindow();
    public static void main(String[] args)
        {
         
            obstacleCourse = new Grid(numberOfRows,numberOfColumns,0,0,1);
            showGrid=new GraphicGrid(obstacleCourse);//shows the obstacle course
            showGrid.setSize(500, 500);
            showGrid.setDefaultCloseOperation(showGrid.EXIT_ON_CLOSE);
            JFrame commandConsole=new FirstWindow();
            commandConsole.setVisible(true);
            obstacleCourse.block(2,2);
    }

      public void ClearGridListener() //implements ActionListener//listener class
        {
            //public void actionPerformed(ActionEvent e)
                {
                    
                    Thread thread=new Thread(new ClearGrid());
                    thread.start();
                }
        }
      private class ClearGrid implements Runnable
      {
          public void run()
          { 
            if(!obstacleCourse.gridIsClear())
                {
                  if(obstacleCourse.frontIsClear() & obstacleCourse.isThereADotFront())
                    {
                        obstacleCourse.move();
                        ClearGridListener();
                    }//end of if
                  else if (obstacleCourse.rightIsClear() & obstacleCourse.isThereADotRight())
                    {
                      obstacleCourse.turnRight();
                      ClearGridListener();
                    }//end of if
                  else if (obstacleCourse.leftIsClear() & obstacleCourse.isThereADotLeft())
                    {
                       obstacleCourse.turnLeft();
                       ClearGridListener();
                    }
                  else if (!obstacleCourse.isThereADotFront() & !obstacleCourse.isThereADotRight() & !obstacleCourse.isThereADotLeft())
                    {
                        for (int mover=1; obstacleCourse.frontIsClear();mover++)
                            {
                            int counter=0;
                            if (mover>=obstacleCourse.getRows())
                                {
                                    mover=1;
                                }
                             if (mover>=obstacleCourse.getColumns())
                                {
                                    mover=1;
                                }
                             while (counter<mover)
                                {
                                    if (obstacleCourse.frontIsClear())
                                        {
                                            obstacleCourse.move();
                                            counter++;
                                        }
                                    else counter++;
                                }
                            }
                        ClearGridListener();
                    }
                  
                }//end of of big IF
                }//end of method
        }//end of inner class
public void CreateGridListener() //implements ActionListener//listener class
        {
            //public void actionPerformed(ActionEvent e)
                {
                    Thread thread=new Thread(new CreateGrid());
                    thread.start();
                }
        }
public class CreateGrid implements Runnable
        {
          public void run()
          {
            numberOfRows=Integer.parseInt(commandConsole.numberOfRows);
            numberOfColumns=Integer.parseInt(commandConsole.numberOfColumns);
            obstacleCourse=new Grid(numberOfRows,numberOfColumns,0,0,1);
            showGrid=new GraphicGrid(obstacleCourse);//shows the obstacle course
            showGrid.setSize(800,500);
            showGrid.setDefaultCloseOperation(showGrid.EXIT_ON_CLOSE);
          }//end of method
        }//end of inner class
public static class PlaceBlocksListener implements ActionListener//listener class
        {
            public void actionPerformed(ActionEvent e)
                {
                    Thread thread=new Thread(new PlaceBlocks());
                    thread.start();
                }
        }
private static class PlaceBlocks implements Runnable
        {
          public void run()
          {
            String rowsAsString=rowTextField.getText();
            String columnsAsString=columnTextField.getText();
            int rowBlock=Integer.parseInt(rowsAsString)-1;
            int columnBlock=Integer.parseInt(columnsAsString)-1;
            obstacleCourse.block(rowBlock, columnBlock);
          }//end of method
        }//end of inner class
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FirstWindow.java
 *
 * Created on Mar 24, 2010, 4:26:28 PM
 */

package myfirstcookie;

/**
 *
 * @author Darrel and Camila
 */
public class FirstWindow extends javax.swing.JFrame {

    /** Creates new form FirstWindow */
    public FirstWindow() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        numberOfRowsField = new javax.swing.JTextField();
        numberOfColumnsField = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        clearGrid = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        CreateNewGridButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("The Widow Maker");
        setAlwaysOnTop(true);

        numberOfRowsField.setName("numberOfRowsField"); // NOI18N
        numberOfRowsField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                numberOfRowsFieldActionPerformed(evt);
            }
        });

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        clearGrid.setText("Clear Grid");
        clearGrid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearGridActionPerformed(evt);
            }
        });

        jButton2.setText("Place Block");

        jLabel1.setText("Number of Rows");

        jLabel2.setText("Number of Columns");

        jLabel3.setText("Row for block");

        jLabel4.setText("Column for block");

        jLabel5.setText("Moves");

        jTextField5.setName("moveDisplay"); // NOI18N

        CreateNewGridButton.setText("Create New Grid");
        CreateNewGridButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreateNewGridButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(numberOfColumnsField, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(numberOfRowsField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel5)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(58, 58, 58))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(clearGrid)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(CreateNewGridButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(numberOfRowsField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(numberOfColumnsField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(clearGrid, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CreateNewGridButton)
                    .addComponent(jButton2))
                .addContainerGap(37, Short.MAX_VALUE))
        );

        getAccessibleContext().setAccessibleParent(this);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clearGridActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearGridActionPerformed
        // TODO add your handling code here:

        CookieMonster cookie =new CookieMonster();
        cookie.ClearGridListener();
    }//GEN-LAST:event_clearGridActionPerformed

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField3ActionPerformed

    private void CreateNewGridButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateNewGridButtonActionPerformed
        CookieMonster cookie =new CookieMonster();
        numberOfRows=numberOfRowsField.getText();
        numberOfColumns=numberOfColumnsField.getText();
        System.out.println(numberOfRows);
    }//GEN-LAST:event_CreateNewGridButtonActionPerformed

    private void numberOfRowsFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_numberOfRowsFieldActionPerformed
                    numberOfRows=numberOfRowsField.getText();
    }//GEN-LAST:event_numberOfRowsFieldActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FirstWindow().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton CreateNewGridButton;
    public javax.swing.JButton clearGrid;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    public javax.swing.JTextField numberOfColumnsField;
    pub
package myfirstcookie;

/**
 * GraphicGrid is a companion to the Grid class by Rick Mercer.
 * It displays a Grid graphically in a Window. Changes to the Grid
 * object can be seen in the window. A program that has been written
 * to use a Grid can be adapted very easily to use the GraphicGrid.
 * Example:
 * ...
 *   Grid someGrid = new Grid(5,8,3,4,Grid.WEST);  // The Grid object constructed originally
 *   // Make a GraphicGrid object sending the Grid object as a parameter.
 *   GraphicGrid visibleGrid = new GraphicGrid(someGrid);
 * ...
 * This last line will start the Window that displays the Grid someGrid.
 * Any changes to someGrid such as someGrid.move(), or someGrid.turnLeft()
 * will be shown in the window.
 *
 * If an error occurs, a modal dialog message box pops up
 * to inform you that the program will terminate
 *
 * @author Andrew Wilt 12-July-99
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;

public class GraphicGrid extends JFrame {

      public static void main( String[] args )
      {
        // When run, you can play with graphic grids
        new GraphicGrid( );
      }

  /**
   * The Frame that holds the Grid to be displayed graphically
   * The size of the Window is set according to the size of the Grid.
   * @ param Grid  The Grid object that is going to be sending stateChanges.
   */
  public GraphicGrid(Grid g)
  {
    super("Watch the actions of the grid");
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e){
        System.exit(0);
      }
    } );
    myGrid = g;
    setSize(g.getColumns()*spotWidth + spacing, g.getRows()*spotHeight + spacing);
    myPanel = new GraphicGridPanel(g, spotWidth, spotHeight);
    myGrid.setGridListener(this);
    JSlider speedBar = new JSlider(JSlider.HORIZONTAL);
    speedBar.addChangeListener(new ChangeListener(){
      public void stateChanged(ChangeEvent e){
        JSlider source = (JSlider)e.getSource();
        if(!source.getValueIsAdjusting())
          myGrid.setSleepTime((int)source.getValue()*10);
      }
    });
    Container contentPane = getContentPane();
    contentPane.add(myPanel, "Center");
    contentPane.add(speedBar, "South");
    this.show();
  }

  public GraphicGrid(){
    super("Interactive Grid");
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e){
        System.exit(0);
      }
    } );
    numRows = defaultNRows;
    numCols = defaultNColumns;
    myGrid = new Grid(defaultNRows, defaultNColumns, 0, 0, Grid.EAST);
    myPanel = new GraphicGridPanel(myGrid, spotWidth, spotHeight);
    myGrid.setGridListener(this);
    controls = makeButtons();
    Dimension gridSize = myPanel.getSize();
    Dimension controlSize = controls.getSize();
    setSize(new Dimension(Math.max(gridSize.width, controlSize.width)+30, (gridSize.height + controlSize.height)));
    Container contentPane = getContentPane();

    contentPane.add(myPanel, "Center");
    contentPane.add(controls, "South" );
    this.show( );
  }
  /**
   * Called by the Grid object whenever the state changes.
   * @param char[][] 2D Array of chars that represents the Grid.
   */
  public void stateChanged(char[][] rect){
    myPanel.stateChanged(rect);
  }

  public JPanel makeButtons(){
    JPanel gridControls = new JPanel();
    gridControls.setOpaque(true);
    gridControls.setLayout(new BoxLayout(gridControls, BoxLayout.Y_AXIS));
    MyTextFieldListener textListener = new MyTextFieldListener();

    // First row of objects
    JPanel firstRow = new JPanel();
    firstRow.setOpaque(true);
    JButton newGrid = new JButton("newGrid");
    final GraphicGrid outside = this;
    newGrid.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        if(moverRowNum < 0 || moverColNum < 0)
          myGrid = new Grid(numRows, numCols);
        else
          myGrid = new Grid( numRows, numCols, moverRowNum, moverColNum, currentDirection );
        myPanel.setGrid(myGrid);
        myGrid.setGridListener(outside);
        frontIsClearLabel.setText(String.valueOf(myGrid.frontIsClear()));
        Dimension gridSize = myPanel.getSize();
        Dimension controlSize = controls.getSize();
        setSize(new Dimension(Math.max(gridSize.width, controlSize.width), (gridSize.height + controlSize.height)));
        repaint();
      }
    });
    firstRow.add(newGrid);

    firstRow.add(new JLabel("nRows", SwingConstants.RIGHT));

    JTextField nRows = new JTextField(textFieldWidth);
    nRows.setText(String.valueOf(defaultNRows));
    nRows.getDocument().addDocumentListener(textListener);
    nRows.getDocument().putProperty("name", "nRows");
    firstRow.add(nRows);

    firstRow.add(new JLabel("nCols", SwingConstants.RIGHT));

    JTextField nCols = new JTextField(textFieldWidth);
    nCols.setText(String.valueOf(defaultNColumns));
    nCols.getDocument().addDocumentListener(textListener);
    nCols.getDocument().putProperty("name", "nCols");
    firstRow.add(nCols);
    gridControls.add(firstRow);

    // Second row of objects
    JPanel secondRow = new JPanel();
    secondRow.setOpaque(true);
    secondRow.add(new JLabel("moverRow", SwingConstants.RIGHT));

    JTextField moverRow = new JTextField(textFieldWidth);
    moverRow.setText(String.valueOf(0));
    moverRow.getDocument().addDocumentListener(textListener);
    moverRow.getDocument().putProperty("name", "moverRow");
    secondRow.add(moverRow);

    secondRow.add(new JLabel("moverCol", SwingConstants.RIGHT));

    JTextField moverCol = new JTextField(textFieldWidth);
    moverCol.setText(String.valueOf(0));
    moverCol.getDocument().addDocumentListener(textListener);
    moverCol.getDocument().putProperty("name", "moverCol");
    secondRow.add(moverCol);

    secondRow.add(new JLabel("moverDirection", SwingConstants.RIGHT));

    String[] dirList = {"NORTH", "SOUTH", "EAST", "WEST"};
    JComboBox moverDirection = new JComboBox( dirList );
    moverDirection.setSelectedIndex( 2 );

    moverDirection.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        currentDirection =
         getDirection((String)((JComboBox)e.getSource()).getSelectedItem());
      }
    });

    secondRow.add(moverDirection);
    gridControls.add(secondRow);
    gridControls.add(Box.createRigidArea(new Dimension(0,5)));

    // Fourth row of objects
    JPanel fourthRow = new JPanel();
    fourthRow.setOpaque(true);
    JButton block = new JButton("block");
    block.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        myGrid.block(blockRowNum, blockColNum);
      }
    });
    fourthRow.add(block);

    fourthRow.add(new JLabel("row", SwingConstants.RIGHT));

    JTextField blockRow = new JTextField(textFieldWidth);
    blockRow.setText(String.valueOf(blockRowNum));
    blockRow.getDocument().addDocumentListener(textListener);
    blockRow.getDocument().putProperty("name", "blockRow");
    fourthRow.add(blockRow);

    fourthRow.add(new JLabel("cols", SwingConstants.RIGHT));

    JTextField blockCol = new JTextField(textFieldWidth);
    blockCol.setText(String.valueOf(blockColNum));
    blockCol.getDocument().addDocumentListener(textListener);
    blockCol.getDocument().putProperty("name", "blockCol");
    fourthRow.add(blockCol);

    JButton putDown = new JButton("putDown");
    putDown.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        myGrid.putDown(putDownRowNum, putDownColNum);
      }
    });
    fourthRow.add(putDown);

    fourthRow.add(new JLabel("row", SwingConstants.RIGHT));

    JTextField putDownRow = new JTextField(textFieldWidth);
    putDownRow.setText(String.valueOf(putDownRowNum));
    putDownRow.getDocument().addDocumentListener(textListener);
    putDownRow.getDocument().putProperty("name", "putDownRow");
    fourthRow.add(putDownRow);

    fourthRow.add(new JLabel("cols", SwingConstants.RIGHT));

    JTextField putDownCol = new JTextField(textFieldWidth);
    putDownCol.setText(String.valueOf(putDownColNum));
    putDownCol.getDocument().addDocumentListener(textListener);
    putDownCol.getDocument().putProperty("name", "putDownCol");
    fourthRow.add(putDownCol);
    gridControls.add(fourthRow);

    // Fifth row of objects
    JPanel fifthRow = new JPanel();
    fifthRow.setOpaque(true);
    JButton move = new JButton("move");
    move.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        myGrid.move( );
      }
    });
    fifthRow.add(move);

    JButton turnLeft = new JButton("turnLeft");
    turnLeft.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        myGrid.turnLeft();
      }
    });
    fifthRow.add(turnLeft);

    JButton pickUp = new JButton("pickUp");
    pickUp.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        myGrid.pickUp();
      }
    });
    fifthRow.add(pickUp);

    JCheckBox showPath = new JCheckBox("showPath");
    showPath.setSelected(true);
    showPath.addItemListener(new ItemListener(){
      public void itemStateChanged(ItemEvent e){
        myGrid.toggleShowPath();
      }
    });
    fifthRow.add(showPath);
    gridControls.add(fifthRow);

    // Sixth line of objects
    JPanel sixthRow = new JPanel();
    sixthRow.setOpaque(true);
    JButton frontIsClear = new JButton("frontIsClear");
    frontIsClear.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        frontIsClearLabel.setText(String.valueOf(myGrid.frontIsClear()));
      }
    });
    sixthRow.add(frontIsClear);

    frontIsClearLabel = new JLabel(String.valueOf(myGrid.frontIsClear()), SwingConstants.LEFT);
    sixthRow.add(frontIsClearLabel);

    gridControls.setBorder(
      BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Grid Commands"),
          BorderFactory.createEmptyBorder(5,5,5,5)));

    gridControls.setSize(gridControls.getPreferredSize());
    return gridControls;
  }

  private int getNumber(String txt){
    try{
      retu
package myfirstcookie;

import java.util.*;
import javax.swing.JOptionPane;

/**
  A class aimed to help students taking an introductory problem-solving
  and programming class while using Rick Mercer's Computing Fundamentals
  textbook in either C++ or Java. The Grid class supports the understanding
  of using existing classes, sending messages, distinguishing between objects
  and classes, learning sequentual control, selection, repetition, functions,
  arugment/parameter associations,and so on.

  @author Rick Mercer inspired by Rich Pattis' Karel the Robot & Disney's Epcot Center
*/

// This class should be used only in conjuction with
//  Computing Fundamentals with Java
//  Rick Mercer, Franklin, Beedle, and Associates

// Last Modified 13-July-99: by Andrew Wilt
//  Changed so the state of a Grid object can be
//  viewed graphically by the GraphicGrid class
//  Changes--
//    - Added setListener(Grid)  which sets the object that
//      is listening to this Grid.
//    - Added updateState( )  This method calls the stateChanged method
//      whenever the state of this Grid changes (by turnLeft( ), move( ), etc.)
//    - Added cloneArray( ) A method that returns a clone of a char array.
//      This clone is sent to the Grid.
//    - Added setSleepTime( ) so that the period between changes can be adjusted.
//   Update documentation. There is a bug when turning from intersection with a thing on it
// Modified by Rick Mercer 6-Jan-99:
//   Uppercased the four directions (east is not EAST),
//   Improved error handling
// Modified by Rick Mercer 6-Jan-99:
//   Uppercased the four directions (east is not EAST),
//   Improved error handling
// Modified by Rick Mercer 15-Sep-01:
//   Removed the need for Direction.java and GridListener.java in order to
//   reduce the number of files required to ruin a grid program
// Modified by Rick Mercer 14-Feb-02:
//   Improved error handling for putDown and block
//

public class Grid
{
  // class constants avaialable to wherever an instance of this class is constructed
  public final static int NORTH = 0;
  public final static int EAST = 1;
  public final static int SOUTH = 2;
  public final static int WEST = 3;
  public final static int MAX_ROWS = 22;
  public final static int MAX_COLUMNS = 36;

  //--class constant available only to other classes in this folder
  final static char intersectionChar = '.';
  final static char beenThereChar = ' ';
  final static char blockChar = '#';
  final static char thingHereChar = 'O';
  final static char moverOnThingChar = '&';
  final static char moverNorth = '^';
  final static char moverSouth = 'v';
  final static char moverEast = '>';
  final static char moverWest = '<';

//--instance variables
  private Random ranNum;
  private int lastRow;       // the number of the last row
  private int lastCol;       // the number of the last column
  private char[][] rectangle = new char[MAX_ROWS][MAX_COLUMNS];
  private int currentRow;    // The row where the mover is
  private int currentCol;    // The column where the mover is
  private char icon;         // the symbol in the currentRow, currentCol
  private int facing;
  private boolean showPath;       // whether or not the path is shown
  private GraphicGrid myListener; // listener object to be notified when state changes.
  private boolean turningLeft = false;
  private int sleepTime = 500;    // Default sleep time of 500 milliseconds

//--Constructors (there are two)

/**
  * Construct a totalRows by totalCols Grid object with the mover's start
  * position and direction are fixed by the arguments.
  * @param totalRows The maximum number of rows (Note the first row == 0)
  * @param totalCols The maximum number of columns (Note the first column == 0)
  * @param startRow The row in which the mover begins
  * @param startCol The column in which the mover begins
  * @param startDirection The direction in which the mover will face.
  * This parameter should be specified as Grid.NORTH, Grid.EAST,
  * Grid.SOUTH, or Grid.WEST. However, you could actually send use an int argument
  *  of 0 (Grid.NORTH), 1 (Grid.EAST) , 2, or 3 (Grid.WEST), but it's not as clear.
  */
public Grid( int totalRows,
             int totalCols,
             int startRow,
             int startCol,
             int startDirection )
{
  // Check the initial position of the mover is within the Grid
  lastRow = totalRows-1;
  lastCol = totalCols-1;
  showPath = true;  // Show path when true, when it's false keep the intersection visible
  int r, c;
  for( r = 0; r <= lastRow; r++ )
  {
    for(c = 0; c <= lastCol; c++ )
    {
      rectangle[r][c] = intersectionChar;
    }
  }

  currentRow = startRow;
  currentCol = startCol;
  facing = startDirection;
  setIcon( );
  rectangle[currentRow][currentCol] = icon;
}

/** Construct a totalRows by totalCols Grid object that has a border all
  * around it except for one exit placed in a random spot with the mover's
  * start position at some random location inside the Grid object facing a
  * random direction (Grid.NORTH, Grid.SOUTH, Grid.EAST, or Grid.WEST).
  */
  public Grid( int totalRows, int totalCols )
  {
    if( totalRows > MAX_ROWS )
      error( "row argument " + totalRows + " too large" );
    else if( totalRows < 1 )
      error(totalRows + " rows must be >= 1");
    if( totalCols > MAX_COLUMNS )
      error( "column argument " + totalCols + " too large" );
    if( totalCols < 1 )
      error( totalCols + " columns must be >= 1" );

    // Set up a border on the edges with one escape route
    ranNum = new Random( );

    showPath = true;  // Show path when true, when it's false 0 keep the intersection visible
    lastRow = totalRows - 1;
    lastCol = totalCols - 1;

    int r, c;
    for( r = 0; r <= lastRow; r++ )
    {
      for( c = 0; c <= lastCol; c++ )
      {
        rectangle[r][c] = intersectionChar;
      }
    }

    for( c = 0; c <= lastCol; c++ )
    {
      rectangle[0][c] = blockChar;         // block first row
      rectangle[lastRow][c] = blockChar;   // blocked last row
    }

    for( r = 0; r <= lastRow; r++ )
    {
     rectangle[r][0] = blockChar ;        // block first column
     rectangle[r][lastCol] = blockChar ;  // block last column
    }

    // Put the mover somewhere in the Grid, but NOT a border
    ranNum = new Random( );
    currentRow = Math.abs(ranNum.nextInt( ) ) % (lastRow-1) + 1;
    currentCol = Math.abs(ranNum.nextInt( ) ) % (lastCol-1) + 1;

    // Pick a random direction
    int direct = Math.abs(ranNum.nextInt( ) ) % 4;
    if( direct == 0 )
      facing = NORTH;
    else if( direct == 1 )
      facing = EAST;
    else if( direct == 2 )
      facing = SOUTH;
    else
      facing = WEST;

    setIcon( );
    rectangle[currentRow][currentCol] = icon;

    // Put one opening on any of the four edges
    if( Math.abs( ranNum.nextInt( ) ) % 2 == 0 )
    { // set on top or bottom at any column
      c = Math.abs(ranNum.nextInt( ) ) % lastCol;

      if( c == 0 )
        c++;           // avoid upper and lower left corner exits (see below)
      if( c == lastCol )
        c--;           // avoid upper and lower right corner exits (see below)

      if( Math.abs( ranNum.nextInt( ) ) % 2 == 0 )
        r = lastRow;  // half the time. on the bottom
      else
        r = 0;        // the other half, on the top
    }
    else
    { // set on left or right at any column
      r = Math.abs(ranNum.nextInt( ) ) % lastRow;

      if( r == 0 )    // avoid upper right and left corner exits
        r++;
      if( r == lastRow )
        r--;          // avoid  lower left and  lower right exits

      if( Math.abs( ranNum.nextInt( ) ) % 2 == 0 )
        c = lastCol;  // half the time in the right column
      else
        c = 0;        // the other half, put on left
    }
    rectangle[r][c] = intersectionChar;
  }

// -accessors

/** The row in which this Grid object's mover is currently located.
  * @return the row where the mover currently is. Note: the first row is 0
  */
  public int moverRow( )
  {
    return currentRow;
  }

/** The column in which this Grid object's mover is currently located
  * @return the row where the mover currently is. Note: the first column is 0
  */
  public int moverColumn( )
  {
    return currentCol;
  }

/** Find out how many rows are in this particular Grid object
  * @return the number of rows in this Grid object
  */
  public int getRows( )
  { // lastRow is the number of the last row as in 0..lastRow
    // so the total number of rows is one more than that
    return lastRow + 1;
  }

/** Find out how many columns are in this particular Grid object
  * @return the number of columns in this Grid object
  */
  public int getColumns( )
  { // lastCol is the number of the last column as in 0..lastCol
    // so the total number of columns is one more than that
    return lastCol + 1;
  }

/** Find out if the mover could move one space forward
  * @return true if the mover could currently move forward by one space
  */
  public boolean frontIsClear( )
  {
    if( facing == NORTH )
    {
      if( currentRow == 0 )
        return false;
      else if( rectangle[currentRow - 1][currentCol] == blockChar )
        return false;
      else
        return true;
    }
    else if( facing == EAST )
    {
      if( currentCol == lastCol )
        return false;
      else if( rectangle[currentRow][currentCol+1] == blockChar )
         return false;
       else
         return true;
     }
    else if( facing == SOUTH )
    {
      if( currentRow == lastRow )
        return false;
      else if( rectangle [currentRow + 1] [currentCol] == blockChar )
        return false;
      else
        return true;
    }
    else // Must be facing West
    {
      if( currentCol == 0 )
        return false;
      else if( rectangle[currentRow][currentCol-1] == blockChar )
        return false;
      else
        return true;
    }
  }

public boolean rightIsClear( )
  {
    if( facing == WEST )
    {
      if( currentRow == 0 )
        return false;
      else if( rectangle[currentRow - 1][currentCol] == blockChar )
        return false;
      else
        return true;
    }
    else if( facing == NORTH )
    {
      if( currentCol == lastCol )
        retu

Hmm you are obtaining the text in correct manner. I hope there is no problem with the declaration of the string which is being used to get the text from the text box.

private void CreateNewGridButtonActionPerformed (java.awt.event.ActionEvent evt)
{ 
String numberOfRows;//Here
CookieMonster cookie =new CookieMonster();//CookieMonster is my main class
numberOfRows=numberOfRowsField.getText();
numberOfColumns=numberOfColumnsField.getText();
System.out.println(numberOfRows);
} 
//this is my best guess of a listener for the JTextfield
private void numberOfRowsFieldActionPerformed(java.awt.event.ActionEvent evt) { 
String numberOfRows;//And here
numberOfRows=numberOfRowsField.getText();
}

Try this :]

Edited 6 Years Ago by Software guy: n/a

There is no listener to put on your text field at less for that question, the action performed return effectively the data typed in you text field so the error is not where you expect.

I dont now if it is necessary to hide those data membeers in CookieMonster:
numberOfRows and numberOfColumns are declared as int;
and in the class FirstWindow that is a super class of CookieMonster they are declared as String.
I dont now also if it is necesary to initialize the commandConsole variable witch is an instance of FirstWindow out of the main method.
where you redeclare "another" variable with the same name as a JFrame!!!!

Hope this help.

This article has been dead for over six months. Start a new discussion instead.