1

http://www.sudoku.4thewww.com/Grids/grid.jpgのような数独ボード GUI を作成しています。

何らかの理由で、最後の 3*3 ボードしか表示されません。誰かが私が間違っていることを教えてくれたら、とても感謝しています。

import java.awt.*;
import java.util.Random;
import java.awt.*; 
import java.awt.event.*;
import javax.swing.*;

public class gui2 extends JFrame{

private JTextField f[][]= new JTextField[9][9] ;
private JPanel p[][]= new JPanel [3][3];

public gui2(){
    super("Sudoku");
    setLayout(new GridLayout());

    for(int x=0; x<=8; x++){
        for(int y=0; y<=8; y++){
            f[x][y]=new JTextField(1);
        }
    }

    for(int x=0; x<=2; x++){
        for(int y=0; y<=2; y++){
            p[x][y]=new JPanel(new GridLayout(3,3));
        }
    }
    setLayout(new GridLayout(3,3,5,5));

for(int u=0; u<=2; u++){
    for(int i=0; i<=2; i++){    
        for(int x=0; x<=2; x++ ){
            for(int y=0; y<=2; y++){
            p[u][i].add(f[y][x]);
            }
        }
        add(p[u][i]);
    }
}



}

}
4

1 に答える 1

1

このコードは動作するはずです:

public class Gui2 extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 0;
    private JTextField f[][]= new JTextField[9][9] ;
    private JPanel p[][]= new JPanel [3][3];

    public Gui2(){
        super("Sudoku");

        for(int x=0; x<=8; x++){
            for(int y=0; y<=8; y++){
                f[x][y]=new JTextField(1);
            }
        }

        for(int x=0; x<=2; x++){
            for(int y=0; y<=2; y++){
                p[x][y]=new JPanel(new GridLayout(3,3));
            }
        }

        setLayout(new GridLayout(3,3,5,5));

        for(int u=0; u<=2; u++){
            for(int i=0; i<=2; i++){    
                for(int x=0; x<=2; x++ ){
                    for(int y=0; y<=2; y++){
                        p[u][i].add(f[y+u*3][x+i*3]);
                    }
                }
            add(p[u][i]);
            }
        }
    }
}

問題は次の行にありました: p[u][i].add(f[y][x]);. 同じ 9 つのテキスト フィールドをすべてのパネルに何度も追加していますが、Component複数回追加された は前のコンテナーから削除されます。この行p[u][i].add(f[y+3*u][x+3*i]);は、現在のパネル位置を考慮して、JTextField配列全体を使用します。

于 2013-09-28T23:28:32.717 に答える