java - Observer 和 Observable 没有通知

标签 java 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 构造函数中。当您向对象添加观察者时,这已经发生了。

或者还有更多代码未在此发布吗?

关于java - Observer 和 Observable 没有通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23154804/

相关文章:

javascript - Angular Material dialogRef.afterClosed().subscribe 无法处理错误

java - Observable merge() 检测哪个 observable 被触发

Java Observer 和 Observable 在应用程序之间无法正常工作

java - 如何将可变参数传递给观察者?

java - 是否发出 `onCompleted()` 的性能影响

java - 布局似乎有问题,JButton 在调整窗口大小时显示意外行为

java - 用Java封装

javascript - Angular 2 AsynPipe 不与 Observable 一起工作

java - 匿名内部类示例有效性问题

java - 如何清除android中的后台进程?