samedi 31 octobre 2015

Game of Life, combining JButtons with Observer Pattern

I'm coding the Game of Life in Java for School. My Grid contains Cells, every Cell has a corresponding Button. The Button shows the current condition of every Cell by its Colour. To "combine" the Button and the Cell, I have to use the Observeable Pattern. I have some troubles with using it and can't figure out what I am doing wrong

This is the part of my Cell-Class where I change the value (condition - live or dead) of the Cell. public void setValue(boolean value) { setChanged(); this.value = value; notifyObservers(value); }

The Button should Observe the Cell, so here is the code of my Button Class:

public class MyJButton implements Observer {

private JButton b1;


public JButton setb1(boolean condition){
    this.b1 = new JButton("");
    if (condition == true){
    this.b1.setBackground(Color.WHITE);
    }
    if (condition == false){
        this.b1.setBackground(Color.BLACK);
    }
    this.b1.setBorder( BorderFactory.createRaisedBevelBorder() );
    this.b1.setPreferredSize(new Dimension(10, 10));

    return this.b1;
}



@Override
public void update(Observable arg0, Object arg1) {
    boolean condition = (boolean)arg1;
    if (condition == true){
        this.b1.setBackground(Color.WHITE);
    }
    if (condition == false){
    this.b1.setBackground(Color.BLACK);
    }
}

}

In my GUI Class I add all the Buttons to my GUI and make them observe the Cells.

    public MyJButton[] CellButton;
public void initField() {
    // Creating panel for buttons, which correspond to cells
    cellPanel.removeAll();
    cellPanel.setLayout(new GridLayout(grid.getRows(), grid.getCols()));
    cellPanel.setPreferredSize(new Dimension(size * grid.getCols(), size * grid.getRows()));
    cellPanel.setBackground(Color.BLACK);

    int i;
    int j;
    int x = 0;
    for (i = 0; i < grid.getCols(); i ++){
        for (j = 0; j < grid.getRows(); j++){

            CellButton = new MyJButton[(grid.getRows() * grid.getCols())];
            CellButton[x] = new MyJButton();
            grid.getCell(j, i).addObserver(CellButton[x]);
            cellPanel.add(CellButton[x].setb1(true), BorderLayout.CENTER);
            x++;
        }
        j = 0;
    }       

    //TODO Add the Observer Pattern here 
    //Buttons have to be added to the GUI and connected with the Cell 
    //Use the observer interface of java 

    frame.add(cellPanel, BorderLayout.WEST);
    cellPanel.updateUI();
    frame.pack();
    frame.setVisible(true);
}

Then I tried to Change one Cell (and therefore a Button) to another condition

        this.cellgrid[3][3].setValue(false);

but it didnt work out at all. Maybe someone could help my that would be very kind.

Thanks, Lars.

Aucun commentaire:

Enregistrer un commentaire