0

考虑 JPanel 的结构如下:

在此处输入图像描述

MainPanel 包含两个面板:AdminPanel 和 ReportPanel。
AdminPanel 包含 SetupPanel,其中包含 LogoPanel。

我想将LogoPanel 中的某些更改通知ReportPanel。
为此,我在 ReportsPanel中实现了一个属性更改侦听器。我在 ReportsPanel 中也有对其自身的静态引用。
LogoPanel 使用此静态引用来调用侦听器。
这个解决方案有效,但对我来说似乎并不优雅。

我的问题:有没有更优雅的方式来做到这一点?

4

1 回答 1

1

我制作的解决方案如下:
创建了一个简单的界面

    public interface Follower {

        public void changed(String property);
    }


和一个监听器类:

    public class LogoListener  {

        /**
         * A static reference to this.
         */
        private static LogoListener listener;

        /**
         * Represents the objects to be notified by the listener.
         */
        private static List<Follower> followers;

        /**
         * Create a simple listener to be used by one "notifying"
         * object, and "followers" objects.
         *
         */
        private LogoListener() {
            followers = new ArrayList<Follower>();
            listener = this;
        }

        /**
         * Method to be used by the "notifying" object, to
         * notify followers.
         */
        public void notifyFollowers() {

            for(Follower follower : followers){
                follower.changed("Logo changed");
            }

            System.out.println("Logo changed");

        }

        /**
         * Get the listener instance, or create one if it does not exist.
         *
         * @return the listener
         *              
         */
        public static LogoListener getListener() {

            if(listener == null) {
                listener = new LogoListener();
            }
            return listener;
        }

        /**
         *
         * @param follower
         *       <br>Not null.
         * @throws
         *      <br>IllegalArgumentException if <code>follower</code> is   null.
         */
         public void addFollower(Follower follower) {

            if(follower == null ) {
                throw new
                    IllegalArgumentException("Follower should not be null");
            }

            followers.add(follower);
        }

    }


报告面板(“追随者”或监听对象)实现了追随者接口,这只是意味着覆盖 changed(String message) 方法:

        /* (non-Javadoc)
         * @see listener.Follower#changed(java.lang.String)
         */
        @Override
        public void changed(String msg ) {
            //respond to change goes here 
            System.out.println(msg);

        }


并通过以下方式注册为关注者:

            LogoListener.getListener()
                        .addFollower(this);


徽标面板通过以下方式通知更改:

        LogoListener listener = LogoListener.getListener();
        listener.notifyFollowers();


Commnets 和反馈是最受欢迎的。

于 2015-12-21T10:42:59.890 回答