将用户输入中的整数传递给另一个类

时间:2013-02-17 03:52:26

标签: java string parsing user-interface integer

我在将一个整数从一个类传递到另一个类时遇到问题。

我正在创建一个GUI,用户可以在文本字段中输入一个数字来调整JPanel中网格的大小。

如果我用普通的int写它,如下所示,它可以正常工作,

public int getGridSize() {
    return 6;
}

但是当我尝试更改代码以便从文本字段中获取字符串时(字段中的默认文本是数字“12”),如下所示。

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;
      }
}

无论用户输入什么,网格都保持10x10,就好像它不满足大于0的条件。 网格在名为GridPanel的JPanel中生成。以下是我认为相关的代码。

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;
}

是否已将字符串解析为与整数不同的整数?我的想法是,当applet初始化时它应该从gridSize中取“12”,然后当gridSize中的文本被更改(并且按下“Go”按钮)时,它将使用新维度重绘GridPanel。

1 个答案:

答案 0 :(得分:1)

当我询问你的解析时间时,你说:

  

它由reset()调用它在applet启动时启动。

然后就像我怀疑的那样:你正在构建GUI时在JTextField上调用getText(),并且在用户有任何时间与GUI交互之前。有意义的是,文本字段此时不会保留任何逻辑值。

正如我在上面的评论中所述,解决方案是在事件监听器(如ActionListener)中进行解析。这意味着解析将在用户触发事件时发生,例如按下触发ActionListener的JButton或单击JLabel从而触发MouseListener。这样,当用户表示他们已完成输入信息时,您可以从用户那里获取信息,并且需要进行计算。

例如:

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");
      }
   }

}