Pregunta

Dentro de este programa, necesitamos crear una cuadrícula de 8x8 de "LifeCell" widgets El instructor no mencionó que los widgets tenían que ser un objeto de Shape , así que seguí adelante y usé la clase GridLayout . La clase GridLayout funciona bien (por lo que sé, ya que no hay ayuda visual para confirmar). El objetivo del programa es jugar el Juego de la Vida, donde un usuario puede hacer clic en uno de los Los widgets de LifeCell y alternan entre estados "vivos" o "muertos".

Mi pregunta se basa en gran medida en pintar las celdas. Podría ser un problema con mi código, pero no estoy 100% seguro.

Program2.java

public class Program2 extends JPanel implements ActionListener {
private LifeCell[][] board; // Board of life cells.
private JButton next; // Press for next generation.
private JFrame frame; // The program frame.

public Program2() {
    // The usual boilerplate constructor that pastes the main
    // panel into a frame and displays the frame. It should
    // invoke the "init" method before packing the frame
    frame = new JFrame("LIFECELL!");
    frame.setContentPane(this);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.init();
    frame.pack();
    frame.setVisible(true);
}
    public void init() {
    // Create the user interface on the main panel. Construct
    // the LifeCell widgets, add them to the panel, and store
    // them in the two-dimensional array "board". Create the
    // "next" button that will show the next generation.
    LifeCell[][] board = new LifeCell[8][8];
    this.setPreferredSize(new Dimension(600, 600));
    this.setBackground(Color.white);
    this.setLayout(new GridLayout(8, 8));
    // here is where I initialize the LifeCell widgets
    for (int u = 0; u < 8; u++) {
        for (int r = 0; r < 8; r++) {
            board[u][r] = new LifeCell(board, u, r);
            this.add(board[u][r]);
            this.setVisible(true);

        }
    }

LifeCell.java

 public class LifeCell extends JPanel implements MouseListener {
   private LifeCell[][] board; // A reference to the board array.
   private boolean alive;      // Stores the state of the cell.
   private int row, col;       // Position of the cell on the board.
   private int count;          // Stores number of living neighbors.

   public LifeCell(LifeCell[][] b, int r, int c) {
       // Initialize the life cell as dead.  Store the reference
       // to the board array and the board position passed as
       // arguments.  Initialize the neighbor count to zero.
       // Register the cell as listener to its own mouse events.
       this.board = b;
       this.row = r;
       this.col = c;
       this.alive = false;
       this.count = 0;
       addMouseListener(this);
   }   

y aquí está el método paintComponent :

   public void paintComponent(Graphics gr) {
       // Paint the cell.  The cell must be painted differently
       // when alive than when dead, so the user can clearly see
       // the state of the cell.
           Graphics2D g = (Graphics2D) gr;
           super.paintComponent(gr);
           g.setPaint(Color.BLUE);
   }

No necesito la solución exacta para solucionarlo, pero estoy muy ingenioso tratando de que funcione.

Gracias.

EDITAR:

Agregué más segmentos de la clase Program2.java, puedo volver mañana. Me voy a la cama, agradezco toda la ayuda chicos.

EDITAR # 2:

Mi verdadera confusión llega cuando lleno mi marco con un GridLayout de 8x8 cada "celda" individual " por falta de mejores palabras es del tipo LifeCell . ¿Cómo puedo pintar cada LifeCell en diferentes colores? Si eso tiene algún sentido para ustedes, puedo tratar de revisarlo tanto como pueda. Y camickr, miraré ese sitio web, gracias.

La asignación se puede encontrar aquí para evitar cualquier confusión con respecto a mi pregunta y / o el fragmento de código.

¿Fue útil?

Solución

 texto alternativo

Estás en el camino correcto.

Si desea utilizar un componente existente (como JPanel, JLabel, JButton, etc.) es mucho mejor que respete lo que el componente ya hace, y simplemente parametrice lo que se necesita.

Entonces, en su caso, está utilizando un JPanel, este (y otros JComponents) tienen una propiedad background que puede cambiar. Entonces, en lugar de tratar de pintar el componente usted mismo (que es lo que está fallando en este momento) simplemente establezca ese valor y deje que la pintura pinte en sí.

Puede agregar un " getLifeColor " que devuelven diferentes colores según el estado de la celda:

   private Color getLifeColor() {
       return this.alive?liveColor:deadColor;
   } 

Y luego haga que la celda pinte el fondo con este color:

  public void paintComponent(Graphics gr) {
       setBackground( getLifeColor() );
       super.paintComponent( gr );
  }

Después de eso, solo tiene que configurar el estado de la celda como vivo o muerto y el componente aparecerá con el color correspondiente:

 texto alternativo

Aquí está el breve ejemplo correcto e independiente (SSCCE) del código que publicó + el color vivo / muerto uso. Creo que puedes continuar desde allí.

Otros consejos

JPanel no tiene un tamaño preferido predeterminado o contenido visible. necesitará agregar algún tipo de componente visible (por ejemplo, JLabel) o darle un tamaño preferido.

además de esto, su diseño debería funcionar si lo configuró de la siguiente manera:

JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++)
    for (int j = 0; j < 8; j++)
        cp.add(new JLabel(i + "-" + j));
frame.pack();
frame.setVisible(true);

¿Por qué incluso tiene un método paintComponent () para su LifeCell? No hay necesidad de hacer pintura personalizada. Puede cambiar el color de fondo de cualquier componente usando:

setBackground( Color.BLUE ) 

Aparte de eso, tu pregunta no tiene sentido para mí. Primero declaras que necesitas usar un objeto Shape, pero no veo un objeto Shape en ninguna parte de tu código, entonces, ¿por qué confundiste la pregunta al mencionar eso?

Realmente no entiendo su pregunta y no tenemos suficiente código para proporcionar sugerencias reales.

Si necesita más ayuda, publique su SSCCE mostrando el problema.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top