JLabel值在GUI中没有变化

时间:2017-10-07 08:31:30

标签: java user-interface model-view-controller jlabel

public class Glass extends Observable {
   int amount;
   int capacity;
   public Glass(int amount, int capacity){
       this.amount = amount;
       this.capacity = capacity;
   }
   public int getAmount(){
       return this.amount;
   }

   @Override
   public synchronized void addObserver(Observer o) {
       super.addObserver(o);
       this.setChanged();
       this.notifyObservers();
   }
}

public class GlassLiquidView extends JLabel implements Observer {

    public void update(Observable o, Object arg) {
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                this.setText("" + ((Glass) o).getAmount());
            }
        });

    }

public class GUIControl {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showGUI();
            }
        });
    }

    public static void showGUI() {  

        JFrame frame = new JFrame("MyFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        GlassLiquidView firstGlassLiqView = new  GlassLiquidView();
        GlassLiquidView secondGlassLiqView = new  GlassLiquidView();
        GlassLiquidView thirdGlassLiqView = new  GlassLiquidView();

        Glass [] glasses = new int[3];
        glasses[0] = new Glass(6,6);
        glasses[1] = new Glass(1,4);
        glasses[2] = new Glass(0,3);

        glasses[0].addObserver(firstGlassLiqView);
        glasses[1].addObserver(secondGlassLiqView);
        glasses[2].addObserver(thirdGlassLiqView);

        frame.getContentPane().add(firstGlassLiqView);
        frame.getContentPane().add(secondGlassLiqView);
        frame.getContentPane().add(thirdGlassLiqView);
        frame.pack();
        frame.setVisible(true);


        // Amount is changed in from and to glasses
        move(from, to);

        glasses[0].notifyObservers();
        glasses[1].notifyObservers();
        glasses[2].notifyObservers();


    }

调用move后,GUI中的JLabel不会更新。请注意,移动是一种改变"中"的数量的方法。和"到"眼镜。创建眼镜时,JLabel值设置为原始量,并且在调用移动时JLabel上不显示任何更改。但是,当我实际打印金额时,它会被更改。

有人可以告诉我我做错了吗?

0 个答案:

没有答案