user2077261
user2077261

Reputation: 11

Passing an integer from user input to another class

I have a problem getting an integer passed from one class to another properly.

I'm creating a GUI that the user can input a number into a Text Field to resize a grid in a JPanel.

If I write it with an normal int just as below it works fine,

public int getGridSize() {
    return 6;
}

but when I try to change the code so it takes the String from the Text Field (default text in the field is the number "12") as follows.

private void initComponents() {

        gridPanel1 = new lizasummerschol.GridPanel();
        gridSize = new javax.swing.JTextField();

    gridSize.setText("12");
        gridSize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gridSizeActionPerformed(evt);
            }
        });

 private void goBActionPerformed(java.awt.event.ActionEvent evt) {                                    
     size = Integer.parseInt(gridSize.getText());
     gridPanel1.executeUserCommands("reset"); 
     goB.setText("s "+size);
 }                                   


public void setGridSize() {
   this.size = size;
}

public int getGridSize() {
  if (this.size > 0) {
    return this.size;
  }
    else {
       return 10;
      }
}

The grid remains 10x10, regardless of what is input by the user, as if it isn't meeting the condition of being greater than 0. The grid is generated in a JPanel called GridPanel. Here is the code that I think would be relevant.

package lizasummerschol;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;

public class GridPanel extends JPanel implements MouseListener, ActionListener {
    GridJApplet myGridJApplet = new GridJApplet();    
    public int NUMBER_ROWS;
    public int NUMBER_COLS; 
public static int LEFT = 15;
public static int DOWN = 15;
public static int SIZE = 15;

    private int particleColour;
    private int fixedness;
    private int iteration;

    private Graphics bufferGraphics;

    private Image offScreenImage;
    private Image offScreenImageDrawed;
    private Graphics offScreenGraphics;
    private Graphics offScreenGraphicsDrawed;

private int [][] particle;
    private int [][] fixed;

    public GridPanel() {      
            addMouseListener( this );
    reset();
    }
    //Initialise particle with random colours

    private void initialiseRandomly() {
        NUMBER_ROWS = NUMBER_COLS = myGridJApplet.getGridSize();    
        particle = new int[NUMBER_ROWS][NUMBER_COLS];
        fixed = new int[NUMBER_ROWS][NUMBER_COLS];

      for ( int i=0; i < NUMBER_ROWS; i++ ) {
    for ( int j=0; j < NUMBER_COLS; j++ ) {
        if( Math.random()*3 < 1 ) {
            particle[i][j] = 0 ;
                            } else if ( Math.random()*3 < 2) {
            particle [i][j] = 1 ;
                           } else {
                               particle[i][j] = 2 ;
            }
                    fixed[i][j] = 0;
        }
       }  
    iteration = 1;
}

Is a string that has been parsed to an integer different from an integer? My thought is that it should take the "12" from gridSize when the applet initialises, and then when the text in gridSize is changed (and a "Go" button is pressed) it will redraw the GridPanel with the new dimensions.

Upvotes: 1

Views: 1137

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285401

When I asked when your parsing is taking place, you state:

It's called by reset() It starts when the applet starts.

Then it's as I suspected: you're calling getText() on a JTextField at a time when the GUI is under construction and way before the user has had any time to interact with the GUI. It makes sense that the text field will hold nothing of logical value at this time.

The solution is as I've stated in a comment above, to do your parsing in an event listener such as an ActionListener. This means that the parsing will take place when the user triggers an event such as pressing a JButton that triggers an ActionListener or when clicking on a JLabel and thereby triggering a MouseListener. This way you can get the information from the user when they've indicated that they've completed entering it, and that the calculation needs to be done.

For example:

import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;

public class ParseTextFieldEg extends JApplet {

   @Override
   public void init() {
      try {
         SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
               createGui();
            }
         });
      } catch (InvocationTargetException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }

   private void createGui() {
      ParseTextFieldPanel panel = new ParseTextFieldPanel();
      panel.reset();  // *** calling reset at the wrong time!

      getContentPane().add(panel);
   }

}

class ParseTextFieldPanel extends JPanel {
   private JTextField textField = new JTextField(10);
   private JButton button = new JButton("Push Me");

   public ParseTextFieldPanel() {
      add(textField);
      add(button);

      button.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            reset();  // *** calling reset at the *right* time!
         }
      });
   }

   public void reset() {
      int myInt;
      try {
         myInt = Integer.parseInt(textField.getText());
         JOptionPane.showMessageDialog(this, "myInt is " + myInt);
      } catch (NumberFormatException e) {
         JOptionPane.showMessageDialog(this, "myInt is not yet available or is a non-number");
      }
   }

}

Upvotes: 1

Related Questions