我正在制作一个目前有两个班级的计算器。第一个是扩展JFrame
并创建计算器框架的主类,另一个是为JFrame
创建按钮布局的类。我希望能够将ButtonPanel
类中的文本设置为包含文本区域的主类,但是当我让ButtonPanel
类扩展主类时,它扩展了JFrame
它会导致这些错误。
Exception in thread "main" java.lang.StackOverflowError
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Unknown Source)
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
我的代码
public class Calculator extends JFrame {
public Calculator() {
super("Calculator");
setSize(300,200);
setResizable(false);
setLocationRelativeTo(null);
textBox = new JTextField();
getContentPane().add(textBox,BorderLayout.NORTH);
getContentPane().add(new ButtonPanel(), BorderLayout.CENTER);
setVisible(true);
}
protected JTextField textBox;
public void setString(String str) {
textBox.setText(str);
}
public static void main(String[] args) {
Calculator ge = new Calculator();
}
}
class ButtonPanel extends Calculator {
ButtonPanel() {
JPanel pan = new JPanel();
GridBagLayout gbl = new GridBagLayout();
pan.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = gbc.gridy = 0;
gbc.gridheight = gbc.gridwidth = 1;
JButton button = new JButton("7");
pan.add(button,gbc);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int num = 7;
performAct(num);
}
});
gbc.gridx = 1;
button = new JButton("8");
pan.add(button, gbc);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int num = 8;
performAct(num);
}
});
//Other Buttons not included
void performAct(int buttonNum) {
switch (buttonNum) {
case 0: setString("0");
case 1: setString("1");
case 2: setString("2");
case 3: setString("3");
case 4: setString("4");
case 5: setString("5");
case 6: setString("6");
case 7: setString("7");
case 8: setString("8");
case 9: setString("9");
case 10: setString(" + ");
case 11: setString( " - ");
case 12: setString(" * ");
case 13: setString( " / ");
case 14: setString(" % ");
}
}
}
答案 0 :(得分:4)
class ButtonPanel extends Calculator
ButtonPanel不应该扩展计算器。 ButtonPanel不是JFrame。
ButtonPanel可以扩展JPanel,因为你想向它添加组件。
JPanel pan = new JPanel();
然后就不需要创建JPanel了。您只需设置类的布局并直接添加组件。
查看How to Use GridBagLayout上Swing教程中的部分,了解如何构建课程的更好示例。