【问题标题】:Notify a "remote" JComponent about a change通知“远程”JComponent 发生变化
【发布时间】:2015-12-20 16:23:20
【问题描述】:
考虑一个JPanels的结构如下:
MainPanel 包含两个面板:AdminPanel 和 ReportPanel。
AdminPanel 包含 SetupPanel,其中包含 LogoPanel。
我想通知 ReportPanel 关于 LogoPanel 的某些更改。
为此,我在 ReportsPanel 中实现了一个属性更改监听器。我在 ReportsPanel 中也有对其自身的静态引用。
LogoPanel 使用这个静态引用来调用监听器。
这个解决方案有效,但对我来说似乎并不优雅。
我的问题:有没有更优雅的方法呢?
【问题讨论】:
标签:
java
swing
jpanel
propertychangelistener
【解决方案1】:
我制定的解决方案如下:
创建了一个简单的界面:
public interface Follower {
public void changed(String property);
}
和一个 listener 类:
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);
}
}
报告面板(“follower”或监听对象)实现了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();
非常欢迎社区和反馈。