问题
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