java - 在外部类中创建新实例时出现 StackOverflow 错误

标签 java class instance stack-overflow

我有主类 CalculatorGUI.java 和第二类 KeyHandler.java。如果我在外部类中创建主类的实例(例如 CalculatorGUI one = new CalculatorGUI();),我得到:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError

这是为什么呢?我必须让这个实例使用来自 y 主 GUI 类的变量。

这是我的 CalculatorGUI 类:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

/**
 *
 * @author Michał
 */
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;

public class CalculatorGUI extends javax.swing.JFrame {

    public CalculatorGUI() {
        initComponents();
    }

    private String value = "";

    public void symbolControl(String s) {
        //String str = String.valueOf(s);
        boolean result;
        result = value.endsWith(s);
        if (result == true) {
            int length = value.length();
            value = value.substring(0, length - 1);
        }
    }

    public void setValue(String s) {
        value = s;
    }

    public String getValue() {
        return value;
    }

    public void print(JButton b) {
        value = value + b.getText();
        jTextField1.setText(value);
    }

    KeyHandler keyboard = new KeyHandler();

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        one = new javax.swing.JButton();
        two = new javax.swing.JButton();
        three = new javax.swing.JButton();
        four = new javax.swing.JButton();
        five = new javax.swing.JButton();
        six = new javax.swing.JButton();
        seven = new javax.swing.JButton();
        eight = new javax.swing.JButton();
        nine = new javax.swing.JButton();
        zero = new javax.swing.JButton();
        comma = new javax.swing.JButton();
        multiply = new javax.swing.JButton();
        plus = new javax.swing.JButton();
        equals = new javax.swing.JButton();
        divide = new javax.swing.JButton();
        minus = new javax.swing.JButton();
        del = new javax.swing.JButton();
        lBracket = new javax.swing.JButton();
        rBracket = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Kalkulator");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        one.setText("1");
        one.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                oneActionPerformed(evt);
            }
        });
        one.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                oneKeyPressed(evt);
            }
        });

        two.setText("2");
        two.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                twoActionPerformed(evt);
            }
        });

        three.setText("3");
        three.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                threeActionPerformed(evt);
            }
        });

        four.setText("4");
        four.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fourActionPerformed(evt);
            }
        });

        five.setText("5");
        five.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fiveActionPerformed(evt);
            }
        });

        six.setText("6");
        six.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sixActionPerformed(evt);
            }
        });

        seven.setText("7");
        seven.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sevenActionPerformed(evt);
            }
        });

        eight.setText("8");
        eight.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eightActionPerformed(evt);
            }
        });

        nine.setText("9");
        nine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nineActionPerformed(evt);
            }
        });

        zero.setText("0");
        zero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                zeroActionPerformed(evt);
            }
        });

        comma.setText(".");
        comma.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commaActionPerformed(evt);
            }
        });

        multiply.setText("*");
        multiply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                multiplyActionPerformed(evt);
            }
        });

        plus.setText("+");
        plus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                plusActionPerformed(evt);
            }
        });

        equals.setText("=");
        equals.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                equalsActionPerformed(evt);
            }
        });

        divide.setText("/");
        divide.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                divideActionPerformed(evt);
            }
        });

        minus.setText("-");
        minus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                minusActionPerformed(evt);
            }
        });

        del.setText("<---");
        del.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delActionPerformed(evt);
            }
        });

        lBracket.setText("(");
        lBracket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lBracketActionPerformed(evt);
            }
        });

        rBracket.setText(")");
        rBracket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rBracketActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextField1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(four, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(seven, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(zero, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(one, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(two, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(five, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(eight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(comma, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(nine, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(six, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(three, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(lBracket, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(plus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(del, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(rBracket, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(minus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(equals, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(multiply, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(one)
                    .addComponent(two)
                    .addComponent(three)
                    .addComponent(multiply)
                    .addComponent(divide))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(four)
                    .addComponent(five)
                    .addComponent(six)
                    .addComponent(plus)
                    .addComponent(minus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(seven)
                    .addComponent(eight)
                    .addComponent(nine)
                    .addComponent(lBracket)
                    .addComponent(rBracket))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(zero)
                    .addComponent(comma)
                    .addComponent(del)
                    .addComponent(equals))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                          

    private void equalsActionPerformed(java.awt.event.ActionEvent evt) {                                      
    }                                      

    private void oneActionPerformed(java.awt.event.ActionEvent evt) {                                    
        print(one);
    }                                  

    private void twoActionPerformed(java.awt.event.ActionEvent evt) {                                    
        print(two);
    }                                  

    private void threeActionPerformed(java.awt.event.ActionEvent evt) {                                      
        print(three);
    }                                    

    private void fourActionPerformed(java.awt.event.ActionEvent evt) {                                    
        print(four);
    }                                    

    private void fiveActionPerformed(java.awt.event.ActionEvent evt) {                                    
        print(five);
    }                                    

    private void sixActionPerformed(java.awt.event.ActionEvent evt) {                                    
        print(six);
    }                                  

    private void sevenActionPerformed(java.awt.event.ActionEvent evt) {                                      
        print(seven);
    }                                    

    private void eightActionPerformed(java.awt.event.ActionEvent evt) {                                      
        print(eight);
    }                                    

    private void nineActionPerformed(java.awt.event.ActionEvent evt) {                                    
        print(nine);
    }                                    

    private void zeroActionPerformed(java.awt.event.ActionEvent evt) {                                    
        print(zero);
    }                                    

    private void commaActionPerformed(java.awt.event.ActionEvent evt) {                                      
        String[] symbolArray = {"..", "+.", "-.", "*.", "/.", "(.", ")."};

        value = value + comma.getText();
        for (String symbolArray1 : symbolArray) {
            symbolControl(symbolArray1);
        }
        jTextField1.setText(value);
    }                                    

    private void multiplyActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String symbol1 = "**";
        String symbol2 = ".*";
        value = value + multiply.getText();
        symbolControl(symbol1);
        symbolControl(symbol2);
        jTextField1.setText(value);
    }                                        

    private void divideActionPerformed(java.awt.event.ActionEvent evt) {                                      
        String symbol1 = "//";
        String symbol2 = "./";
        value = value + divide.getText();
        symbolControl(symbol1);
        symbolControl(symbol2);
        jTextField1.setText(value);
    }                                      

    private void plusActionPerformed(java.awt.event.ActionEvent evt) {                                    
        String symbol1 = "++";
        String symbol2 = ".+";
        value = value + plus.getText();
        symbolControl(symbol1);
        symbolControl(symbol2);
        jTextField1.setText(value);
    }                                    

    private void minusActionPerformed(java.awt.event.ActionEvent evt) {                                      
        String symbol1 = "--";
        String symbol2 = ".-";
        value = value + minus.getText();
        symbolControl(symbol1);
        symbolControl(symbol2);
        jTextField1.setText(value);
    }                                    

    private void delActionPerformed(java.awt.event.ActionEvent evt) {                                    
        int length = value.length();
        String parametr = value.substring(0, length - 1);
        value = parametr;
        jTextField1.setText(value);
    }                                  

    private void lBracketActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String symbol1 = ")(";
        String symbol2 = ".(";
        value = value + lBracket.getText();
        symbolControl(symbol1);
        symbolControl(symbol2);
        jTextField1.setText(value);
    }                                        

    private void rBracketActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String symbol1 = ".)";
        String symbol2 = "()";
        value = value + rBracket.getText();
        symbolControl(symbol1);
        symbolControl(symbol2);
        jTextField1.setText(value);
    }                                        

    private void oneKeyPressed(java.awt.event.KeyEvent evt) {                              
        // TODO add your handling code here:
    }                              

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CalculatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CalculatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CalculatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CalculatorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CalculatorGUI().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify                    
    private javax.swing.JButton comma;
    private javax.swing.JButton del;
    private javax.swing.JButton divide;
    private javax.swing.JButton eight;
    private javax.swing.JButton equals;
    private javax.swing.JButton five;
    private javax.swing.JButton four;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JButton lBracket;
    private javax.swing.JButton minus;
    private javax.swing.JButton multiply;
    private javax.swing.JButton nine;
    public javax.swing.JButton one;
    private javax.swing.JButton plus;
    private javax.swing.JButton rBracket;
    private javax.swing.JButton seven;
    private javax.swing.JButton six;
    private javax.swing.JButton three;
    private javax.swing.JButton two;
    private javax.swing.JButton zero;
    // End of variables declaration                  
}

KayHandler.java:

package gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;



public class KeyHandler implements KeyListener {

    CalculatorGUI elo = new CalculatorGUI();

    /** Handle the key typed event from the text field. */
    @Override
    public void keyTyped(KeyEvent e) {

    }

    /** Handle the key-pressed event from the text field. */
    @Override
    public void keyPressed(KeyEvent e) {

    }

    /** Handle the key-released event from the text field. */
    @Override
    public void keyReleased(KeyEvent e) {

    }

最佳答案

你有

class CalculatorGUI {
    KeyHandler keyboard = new KeyHandler();
}

class KeyHandler {
    CalculatorGUI elo = new CalculatorGUI();
}

创建一个新的 CalculatorGUI 创建一个新的 KeyHandler,它创建一个新的 CalculatorGUI,它创建一个新的 KeyHandler,它创建一个新的 CalculatorGUI,它创建一个新的 KeyHandler,它创建一个新的 CalculatorGUI,它创建一个新的 KeyHandler,.. . 计算器

关于java - 在外部类中创建新实例时出现 StackOverflow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27603527/

相关文章:

java - 在Java中通过restTemplate从rest webservice获取垃圾值

java - 创建android应用程序的多个副本

java - 在 Java 类 DecimalFormat 中,小数点左侧的主题标签有什么作用?

java - API 测试 - 在使用 json 的 resassured 时获取方括号中的值,导致断言失败

java - 如何在paint()方法之外的小程序中打印

c++ - 在派生类中重写了哪个基类虚析构函数

java - 是否有理由在忽略返回值的情况下调用 obj.getClass() ?

java - 为什么我无法访问在构造函数(Java)中创建的类的实例

c# - 将静态列表分配给非静态列表

python - 如何将 PyObject_IsInstance 与非内置类一起用作第二个参数?