我在将整数从一个类正确传递到另一个类时遇到问题。
我正在创建一个 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;
}
已解析为整数的字符串是否与整数不同?我的想法是,当小程序初始化时,它应该从 gridSize 中获取“12”,然后当 gridSize 中的文本发生更改(并按下“Go”按钮)时,它将使用新尺寸重新绘制 GridPanel。