通过按钮控制某些组件的可见性时,我遇到了stackoverflow错误。
我正在通过setVisible(true)
方法单击按钮,为某些组件设置actionperformed()
。
我在第25和55行上收到stackoverflow错误。
import java.awt.event.*;
public class Expanse extends Frame {
Label l1, l2;
Button b1, b2, b3;
Frame f1;
TextField tf1, tf2;
Expanse() {
l1 = new Label("welcome user");
Font font1 = new Font("SansSerif", Font.BOLD, 25);
Font font2 = new Font("SansSerif", Font.BOLD, 18);
l1.setFont(font1);
addWindowListener(new myWindowAdapter());
l1.setBounds(100, 25, 300, 50);
add(l1);
l2 = new Label("please click any button from below");
l2.setBounds(75, 100, 500, 50);
l2.setFont(font2);
add(l2);
b1 = new Button("add data");
b1.setBounds(70, 175, 100, 50);
add(b1);
b1.addActionListener(new addListener());
b2 = new Button("retrive data");
b2.setBounds(275, 175, 100, 50);
add(b2);
setLayout(null);
setSize(500, 500);
setVisible(true);
tf1 = new TextField("enter amount");
tf2 = new TextField("enter reason");
tf1.setBounds(70, 260, 150, 30);
add(tf1);
tf2.setBounds(70, 320, 150, 30);
add(tf2);
b3 = new Button("write");
b3.setBounds(100, 380, 80, 35);
add(b3);
tf1.setVisible(false);
tf2.setVisible(false);
b3.setVisible(false);
}
public static void main(String a[]) {
Expanse e1 = new Expanse();
}
}
class myWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
class addListener extends Expanse implements ActionListener {
public void actionPerformed(ActionEvent ae) {
tf1.setVisible(true);
tf2.setVisible(true);
b3.setVisible(true);
}
}
在Expanse
构造函数中,您具有:b1.addActionListener(new addListener());
构造一个addListener
对象。addListener
扩展了Expanse
,因此您正在使用Expanse
构造函数创建另一个Expanse
对象。这是一个导致stackoverflow
的过程。解决方法很简单:addListener
没有理由扩展Expanse
。