簡體   English   中英

沒有與觀察者和可觀察者的通知

[英]No notification with Observer & Observable

通過調試,我的問題是notifyObservers(); 我認為該函數未稱為我的更新函數。 在調試中, setChanged(); 函數傳遞一個true並在notifyObservers(); 功能沒有發揮作用。

這是我的代碼:

型號:

public final class Modele_Jeu extends Observable{

public Grille grille;
public Piece piece;

public Modele_Jeu(){

    this.grille = new Grille(22,10);
    this.piece = new Piece();

    this.piece.creer_pieces();
    this.init_piece_in_grille();

    setChanged();
    notifyObservers();

}

private void init_piece_in_grille(){


    for(int i=0;i<5;i++)
    {
        for(int j=3;j<8;j++)
        {
            this.grille.matrice[i][j]= 1; //this.piece.piececourante[0][i];
        }

    }
    System.out.print(this.piece.toString());
    System.out.print(this.grille.toString());


}  
}

Vue:

public class Vue_Jeu extends JFrame implements Observer{

Modele_Jeu jeu;

JPanel container = new JPanel ();

JPanel droite = new JPanel();
JPanel pan = new JPanel (new GridLayout(22,10));
JPanel gauche = new JPanel();

public Vue_Jeu(Modele_Jeu jeu1) {

    this.jeu=jeu1;
    jeu.addObserver(this);
    //jeu1.addObserver(this);

    build();
    this.pan.getComponent(100).setBackground(Color.red);

            addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent arg0) {
            super.windowClosing(arg0);
            System.exit(0);
        }
    });
            this.pack();


}


@Override
public void update(Observable o, Object arg) {
    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    int n=0;
    System.out.print("\n\n"+this.jeu.grille.toString());
    this.jeu.grille = (Grille) arg;
    for(int i =0; i<this.jeu.grille.getlongueur(); i++)
    {
        for(int j=0; j<this.jeu.grille.getlargeur(); j ++)
        {
            if(this.jeu.grille.matrice[i][j]!=0)
            {
                this.pan.getComponent(n).setBackground(Color.red);
            }    
            n++;
        }
    }
}  
}

主要:

public class Tetris {

public static void main(String[] args) {
    Modele_Jeu modele1 = new Modele_Jeu();
    Vue_Jeu vue1 = new Vue_Jeu(modele1);
}
}

調用notifyObservers()的唯一位置是在Modele_Jeu構造函數中。 在向對象添加觀察者時,已經發生了。

還是這里沒有發布更多代碼?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM