0

I've got a main JFrame that creates an instance of a basic notifications JFrame class.

My code for creating the notifications from my main JFrame looks like this:

new Notification(from, msg, time);

I am wondering how i from within my notifications class can access my main JFrame. Basically i want to change setVisible for some components on the main JFrame from within my notifications class.

EDIT

My client.java (main JFrame) calls the notification

public JPanel pnlMidMenuButtons;
/**** code... **/
Notification ntf = new Notification(from, msg, time); // Further down the notification is being called

ImportUI:

public class ImportUI extends Client implements NotificationParent {

public void setImportantFieldsVisible(boolean visible) {
    pnlMidMenuButtons.setVisible(visible);
}

}

NotificationParent:

public interface NotificationParent {
    public void setImportantFieldsVisible(boolean visible);
    public void setAgentName(String agentName);
}

And my notification class:

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 
    }

}

Any ideas whats causing the exception?

4

1 回答 1

1

实际答案将取决于您的需求,但我会创建一个interface(如果您想为某些对象而不是其他对象提供某些功能,甚至可以创建一系列接口)。

public interface NotificationParent {
    public void setImportantFieldsVisible(boolean visible);
}

然后我会在调用者上实现这个接口......

public class ImportUI extends ... implements NotificationParent {
    /*...*/
    public void setImportantFieldsVisible(boolean visible) {
        //....
    }
}

然后我会从一个附加参数到,Notification所以它可以接受NotificationParent...的引用

public class Notification extends ... {

    private NotificationParent parent;
    /*...*/

    public Notification(NotificationParent parent, String from, String msg, Date time) {
        this.parent = parent;
        /*...*/
    }

}

然后,如果您需要,您只需调用一种可用的方法来满足您的要求。

显然,现在您可以拥有更多方法,但这取决于您的要求......

于 2013-09-16T07:26:38.163 回答