java Access parent method from imported child class

雨燕双飞 提交于 2019-12-13 20:06:18

问题


Am a java newbie. Learning from the web. I am stuck with an issue with my code. I have three class. mainclass.java, oneclass.java, twoclass.java. I imported oneclass and twoclass in mainclass.

oneclass has a "next" button. What i want to do is onActionEvent on next btn , call a function from mainclass, which would set the visibility of oneclass to false and twoclass to true. Am posting the whole code for mainclass.java

    package com.mainclass;
    import com.twoframe.twojframes;
    import com.secondframe.secondjframe;

public class MainClass {
    private static com.secondframe.twoclass panel2;
    private static com.twoframe.oneclass panel1;


    private static void openPanel1(){
      panel1 = new com.twoframe.oneclass();
      panel1.setVisible(true);
    }
    public static void toggleVisibility(){
        System.out.println("called from child");
        panel2 = new com.secondframe.twoclass();
        panel2.setVisible(true);
        panel1.setVisible(false);
    }
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                openPanel1();
            }
        });

    }
}

oneclass.java

jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
        {                                         
            // TODO add your handling code here:
           //Basically something like -- mainclass.toggleVisibility();

        } 

Thank you.


回答1:


Assuming the "parent" is a class you're extending and the method you're calling is NOT static, the following should do the trick:

super.toggleVisibility();

If it's a static method - it's even Simpler:

ParentClassName.toggleVisibility();


来源:https://stackoverflow.com/questions/18243102/java-access-parent-method-from-imported-child-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!