あるクラスから別のクラスに整数を適切に渡すのに問題があります。
ユーザーが数値をテキスト フィールドに入力して、JPanel のグリッドのサイズを変更できる GUI を作成しています。
以下のように通常の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;
}
}
0 より大きいという条件を満たしていないかのように、ユーザーが何を入力しても、グリッドは 10x10 のままです。グリッドは 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 が新しい寸法で再描画されます。