我有2个类,一个是Login面板和GUI面板。下面的代码说明当我登录时,它会显示我的GUI并隐藏我的登录。并且在某个时候,当单击注销按钮时,它必须再次调用Login面板。下面的代码导致StackOverFlow错误。我知道那个错误意味着什么,但我不知道如何解决它。当“另一个类”必须在调用它的类上调用某些东西时,有没有更好的解决方案从另一个类调用这些方法?
//Login Panel
public class MyPanel1 extends JFrame implements ActionListener{
MyPanel2 p2 = new MyPanel2();
.
.
public void actionPerformed(ActionEvent e){
//if login is a success
setVisible(false);
p2.setVisible(true);
}
}
//GUI Panel
public class MyPanel2 extends JFrame implements ActionListener{
MyPanel1 p1 = new MyPanel1();
.
.
public void actionPerformed(ActionEvent e){
//if logout button is clicked
setVisible(false);
p1.setVisible(true);
}
}
我的堆栈跟踪:
Exception in thread "main" java.lang.StackOverflowError
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222)
at java.awt.Window.init(Window.java:505)
at java.awt.Window.<init>(Window.java:537)
at java.awt.Frame.<init>(Frame.java:420)
at java.awt.Frame.<init>(Frame.java:385)
at javax.swing.JFrame.<init>(JFrame.java:189)
at Login.<init>(Login.java:29)
at Cashier.<init>(Cashier.java:10)
at Login.<init>(Login.java:9)
at Cashier.<init>(Cashier.java:10)
at Login.<init>(Login.java:9)
at Cashier.<init>(Cashier.java:10)
at Login.<init>(Login.java:9)
答案 0 :(得分:0)
将第一个面板的引用传递给第二个面板的构造函数。
//Login Panel
public class MyPanel1 extends JFrame implements ActionListener{
MyPanel2 p2 = new MyPanel2(this);
.
.
public void actionPerformed(ActionEvent e){
//if login is a success
setVisible(false);
p2.setVisible(true);
}
}
//GUI Panel
public class MyPanel2 extends JFrame implements ActionListener{
MyPanel1 p1;
public MyPanel2(MyPanel1 parent){
this.p1 = parent;
}
public void actionPerformed(ActionEvent e){
//if logout button is clicked
setVisible(false);
p1.setVisible(true);
}
}