【发布时间】:2013-09-16 07:01:07
【问题描述】:
我有一个主要的JFrame,它创建了一个基本通知 JFrame 类的实例。
从我的主要JFrame 创建通知的代码如下所示:
new Notification(from, msg, time);
我想知道我如何从我的通知类中访问我的主要JFrame。基本上我想在我的通知类中更改主要JFrame 上某些组件的 setVisible。
编辑
我的 client.java (main JFrame) 调用通知
public JPanel pnlMidMenuButtons;
/**** code... **/
Notification ntf = new Notification(from, msg, time); // Further down the notification is being called
导入界面:
公共类 ImportUI 扩展客户端实现 NotificationParent {
public void setImportantFieldsVisible(boolean visible) {
pnlMidMenuButtons.setVisible(visible);
}
}
NotificationParent:
public interface NotificationParent {
public void setImportantFieldsVisible(boolean visible);
public void setAgentName(String agentName);
}
还有我的通知类:
public class Notification extends JFrame {
private NotificationParent parent;
/*...*/
public Notification(NotificationParent parent, String from, String msg, Date time) {
this.parent = parent;
parent.setImportantFieldsVisible(false); // Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
}
}
任何想法是什么导致了异常?
【问题讨论】:
-
我强烈建议您不要允许您之外的任何课程框架对其内容进行足够的访问。相反,我可能会考虑使用某种
interface,您可以实现它来公开需要实现的功能。这可以防止Notification类去邮寄和做不应该的事情到主窗口。然后,您只需提供与接口相同类型的参数并将实现的引用传递给它... -
@MadProgrammer 听起来是一个非常好的解决方案。如何实现这样的接口?不太确定我是否遵循逻辑