Communication between two different JFrames?

后端 未结 4 2113
[愿得一人]
[愿得一人] 2020-12-06 07:54

Hello as maybe you have heard about GIMP or something like that which uses different frames As a complete gui so I was wondering how to do such frames communications when bo

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 08:04

    I'm 7 years late, but maybe this is still interesting for you ;) I solved this issue by implementing the Observer-Pattern.

    In my example there is an overview-view (=observer; table from DB) and a detail-view (=observable; contains a row from overview-view). Now I want to edit a (in the overview-view) selected row in the detail-view, click save-button, close the detail-view and notify the changes to (all) observers.

    public interface Observer { 
        public void notifyUpdate(Contact contact); 
    }
    
    public interface Observable {   
        public void addObserver(Observer observer);
    }
    
    public class Detail extends JFrame implements Observable {
        /* multiple observers possible */
        private ArrayList observers;
        /* contact will be modified in detail-view and reported to overview-view */
        private Contact contact;
        public Detail() {
            this.observers = new ArrayList<>();
        }
        @Override
        public void addObserver(Observer observer) {
            this.observers.add(observer);
        }
        /* trigger this methode e.g. by save-button, after modifiing contact */ 
        protected void notifyObservers() {
            /* multiple observers possible */
            Iterator observerIterator = this.observers.iterator();
            while(observerIterator.hasNext()) {
                /* report observer: constact has modified */
                observerIterator.next().notifyUpdate(contact);
            }       
        }
    }
    
    public class Contacts extends JFrame implements Observer {
        private Detail detail;
        public Contacts() {
            detail = new Detail();
            detail.setVisible(true);
            detail.addObserver(this);
        }
        @Override
        public void notifyUpdate(Contact contact) {
            /* notifyUpdate was called from Observable */           
            /* process contact, DB update, update JTable */
        }
    }
    

提交回复
热议问题