[英]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.