gpt4 book ai didi

java - Observer 和 Observable 没有通知

转载 作者:行者123 更新时间:2023-12-01 13:07:32 25 4
gpt4 key购买 nike

通过调试,我的问题是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com