0

GridLayout のパネルがあります

しかし、プログラムを実行しようとすると、100 個のボタンのうち最初のボタンしか表示されません。さらに、残りはカーソルを上に移動したときにのみ表示されます。どうしたの?

これがクラス全体です(Life.CELLS = 10およびCellButtonはJButtonを拡張するクラスです)

public class MainLayout extends JFrame {

    public MainLayout() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(650, 750);
        setLayout(new FlowLayout());
        //setResizable(false);

        final JPanel gridPanel = new JPanel(new GridLayout(Life.CELLS, Life.CELLS));

        for (int i=0; i<Life.CELLS; i++) {
            for (int j=0; j<Life.CELLS; j++) {
                CellButton jb = new CellButton(i, j);
                jb.setPreferredSize(new Dimension(jb.getIcon().getIconHeight(), jb.getIcon().getIconWidth()));
                buttons[i][j] = jb;
                grid[i][j] = false;

                gridPanel.add(jb);
            }
        }
        add(gridPanel);
    }
}

これはCellButtonのコードです

package classes;

import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class CellButton extends JButton {

    private int x;
    private int y;
    boolean alive;
    ImageIcon icon;
    boolean next;

    // icons for grids
    final ImageIcon dead = 
        new ImageIcon(JFrame.class.getResource("/images/image1.gif"));
    final ImageIcon live = 
        new ImageIcon(JFrame.class.getResource("/images/image2.gif"));

    public CellButton(int X, int Y) {
        super();
        x = X;
        y = Y;
        alive = false;
        icon = dead;
        setIcon(icon);
    }   

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public boolean isAlive() {
        return alive;
    }

    public void relive() {
        alive = true;
        icon = live;
        setIcon(icon);
    }

    public void die() {
        alive = false;
        icon = dead;
        setIcon(icon);
    }

    public void setNext(boolean n) {
        next = n;
    }

    public boolean getNext() {
        return next;
    }

    public ImageIcon getIcon() {
        return icon;
    }
}
4

1 に答える 1

0

コードで何か他のことをしている必要があります。使用している正確なコードを投稿してください。次のテストでは、予想どおり、JButton の 10x10 グリッドが表示されます。

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GridLayoutTest
{
 public static void main(String[] args)
 {
  JFrame frame = new JFrame();
  JPanel panel = new JPanel(new GridLayout(10,10,10,10));

  for (int i=0; i<100; i++)
  {
   panel.add(new JButton(String.valueOf(i)));
  }

  frame.add(panel);

  frame.setSize(600,600);
  frame.setVisible(true);
 }
}

編集:
私はあなたの問題を参照してください. getX()andgetY()メソッドをJComponent誤ってオーバーライドしました. int xandint y変数とgetX()andgetY()メソッドを取り除きますJButton。これらは既に提供されています。

于 2011-01-12T13:25:08.930 に答える