我正在尝试使两类Java计算器正常工作(Java的新手),但到目前为止,我还没有成功。下面概述了这两个类,calcFrame用于接口,而calEngine应该进行实际的计算,但是我无法让他们互相交谈。我非常感谢您提供的任何帮助。谢谢。

CalcFrame代码:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;


/**
*A Class that operates as the framework for a calculator.
*No calculations are performed in this section
*/
public class CalcFrame implements ActionListener {

private CalcEngine calc;

private JFrame frame;
private JTextField display;
private JLabel status;

/**
 * Constructor for objects of class GridLayoutExample
 */
public CalcFrame()
{
    makeFrame();
    //calc = engine;
}



/**
 * This allows you to quit the calculator.
 */

// Alows the class to quit.
private void quit()
{
    System.exit(0);


}

// Calls the dialog frame with the information about the project.
private void showAbout()
{
    JOptionPane.showMessageDialog(frame,
                "Group Project",
                "About Calculator Group Project",
                JOptionPane.INFORMATION_MESSAGE);
}



private void makeFrame()
{
    frame = new JFrame("Group Project Calculator");
    makeMenuBar(frame);

    JPanel contentPane = (JPanel)frame.getContentPane();
    contentPane.setLayout(new BorderLayout(8, 8));
    contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10));



    /**
 * Insert a text field
 */
    display = new JTextField();
    contentPane.add(display, BorderLayout.NORTH);

    //Container contentPane = frame.getContentPane();
    contentPane.setLayout(new GridLayout(4, 4));
    JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
    contentPane.add(new JButton("1"));
    contentPane.add(new JButton("2"));
    contentPane.add(new JButton("3"));
    contentPane.add(new JButton("4"));
    contentPane.add(new JButton("5"));
    contentPane.add(new JButton("6"));
    contentPane.add(new JButton("7"));
    contentPane.add(new JButton("8"));
    contentPane.add(new JButton("9"));
    contentPane.add(new JButton("0"));
    contentPane.add(new JButton("+"));
    contentPane.add(new JButton("-"));
    contentPane.add(new JButton("/"));
    contentPane.add(new JButton("*"));
    contentPane.add(new JButton("="));
    contentPane.add(new JButton("C"));

    contentPane.add(buttonPanel, BorderLayout.CENTER);

    //status = new JLabel(calc.getAuthor());
    //contentPane.add(status, BorderLayout.SOUTH);

    frame.pack();
    frame.setVisible(true);
}

/**
 * Create the main frame's menu bar.
 * The frame that the menu bar should be added to.
 */
private void makeMenuBar(JFrame frame)
{
    final int SHORTCUT_MASK =
        Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();


    JMenuBar menubar = new JMenuBar();
    frame.setJMenuBar(menubar);

    JMenu menu;
    JMenuItem item;

    // create the File menu
    menu = new JMenu("File");
    menubar.add(menu);

    // create the Quit menu with a shortcut "Q" key.
     item = new JMenuItem("Quit");
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
        item.addActionListener(new ActionListener() {
                           public void actionPerformed(ActionEvent e) { quit(); }
                       });
    menu.add(item);

    // Adds an about menu.
    menu = new JMenu("About");
    menubar.add(menu);

    // Displays
    item = new JMenuItem("Calculator Project");
        item.addActionListener(new ActionListener() {
                           public void actionPerformed(ActionEvent e) { showAbout(); }
                       });
    menu.add(item);

}


/**
 * An interface action has been performed.
 * Find out what it was and handle it.
 * @param event The event that has occured.
 */
public void actionPerformed(ActionEvent event)
{
    String command = event.getActionCommand();

    if(command.equals("0") ||
       command.equals("1") ||
       command.equals("2") ||
       command.equals("3") ||
       command.equals("4") ||
       command.equals("5") ||
       command.equals("6") ||
       command.equals("7") ||
       command.equals("8") ||
       command.equals("9")) {
        int number = Integer.parseInt(command);
        calc.numberPressed(number);
    }
    else if(command.equals("+")) {
        calc.plus();
    }
    else if(command.equals("-")) {
        calc.minus();
    }
    else if(command.equals("=")) {
        calc.equals();
    }
    else if(command.equals("C")) {
        calc.clear();
    }
    else if(command.equals("?")) {

    }
    // else unknown command.

    redisplay();
}

/**
 * Update the interface display to show the current value of the
 * calculator.
 */
private void redisplay()
{
    display.setText("" + calc.getDisplayValue());
}

/**
 * Toggle the info display in the calculator's status area between the
 * author and version information.
 */

}


CalcEngine:

public class CalcEngine
{
// The calculator's state is maintained in three fields:
//     buildingDisplayValue, haveLeftOperand, and lastOperator.


// The current value (to be) shown in the display.
private int displayValue;
// The value of an existing left operand.
private int leftOperand;

/**
 * Create a CalcEngine.
 */
public CalcEngine()
{
    clear();
}


public int getDisplayValue()
{
    return displayValue;
}

/**
 * A number button was pressed.
 * Either start a new operand, or incorporate this number as
 * the least significant digit of an existing one.
 * @param number The number pressed on the calculator.
 */
public void numberPressed(int number)
{
    if(buildingDisplayValue) {
        // Incorporate this digit.
        displayValue = displayValue*10 + number;
    }
    else {
        // Start building a new number.
        displayValue = number;
        buildingDisplayValue = true;
    }
}

/**
 * The 'plus' button was pressed.
 */
public void plus()
{
    applyOperator('+');
}

/**
 * The 'minus' button was pressed.
 */
public void minus()
{
    applyOperator('-');
}

/**
 * The '=' button was pressed.
 */
public void equals()
{
    // This should completes the building of a second operand,
    // so ensure that we really have a left operand, an operator
    // and a right operand.
    if(haveLeftOperand &&
            lastOperator != '?' &&
            buildingDisplayValue) {
        calculateResult();
        lastOperator = '?';
        buildingDisplayValue = false;
    }
    else {
        keySequenceError();
    }
}

/**
 * The 'C' (clear) button was pressed.
 * Reset everything to a starting state.
 */
public void clear()
{
    lastOperator = '?';
    haveLeftOperand = false;
    buildingDisplayValue = false;
    displayValue = 0;
}

/**
 * @return The title of this calculation engine.
 */
public String getTitle()
{
    return "Java Calculator";
}

/**
 * @return The author of this engine.
 */
public String getAuthor()
{
    return "David J. Barnes and Michael Kolling";
}

/**
 * @return The version number of this engine.
 */
public String getVersion()
{
   return "Version 1.0";
}

/**
 * Combine leftOperand, lastOperator, and the
 * current display value.
 * The result becomes both the leftOperand and
 * the new display value.
 */
private void calculateResult()
{
    switch(lastOperator) {
        case '+':
            displayValue = leftOperand + displayValue;
            haveLeftOperand = true;
            leftOperand = displayValue;
            break;
        case '-':
            displayValue = leftOperand - displayValue;
            haveLeftOperand = true;
            leftOperand = displayValue;
            break;
        default:
            keySequenceError();
            break;
    }
}

/**
 * Apply an operator.
 * @param operator The operator to apply.
 */
private void applyOperator(char operator)
{
    // If we are not in the process of building a new operand
    // then it is an error, unless we have just calculated a
    // result using '='.
    if(!buildingDisplayValue &&
                !(haveLeftOperand && lastOperator == '?')) {
        keySequenceError();
        return;
    }

    if(lastOperator != '?') {
        // First apply the previous operator.
        calculateResult();
    }
    else {
        // The displayValue now becomes the left operand of this
        // new operator.
        haveLeftOperand = true;
        leftOperand = displayValue;
    }
    lastOperator = operator;
    buildingDisplayValue = false;
}

/**
 * Report an error in the sequence of keys that was pressed.
 */
private void keySequenceError()
{
    System.out.println("A key sequence error has occurred.");
    // Reset everything.
    clear();
}


}

最佳答案

“引擎”未初始化”

public CalcFrame() {
    makeFrame();
    calc = new CalcEngine();
}


和:
您应该在按钮上附加一个侦听器,以便在单击按钮时调用actionPerformed()

JButton button = new JButton("1");
button.addActionListener(this);
contentPane.add(button);


应该为每个按钮完成此操作,因此最好首先将按钮放在列表中:

JPanel buttonPanel = new JPanel(new GridLayout(4, 4));

List<JButton> buttons = new ArrayList<JButton>();

buttons.add(new JButton("1"));
buttons.add(new JButton("2"));
buttons.add(new JButton("3"));
buttons.add(new JButton("4"));
buttons.add(new JButton("5"));
buttons.add(new JButton("6"));
buttons.add(new JButton("7"));
buttons.add(new JButton("8"));
buttons.add(new JButton("9"));
buttons.add(new JButton("0"));
buttons.add(new JButton("+"));
buttons.add(new JButton("-"));
buttons.add(new JButton("/"));
buttons.add(new JButton("*"));
buttons.add(new JButton("="));
buttons.add(new JButton("C"));




for(JButton button : buttons){
     buttonPanel.add(button);
     button.addActionListener(this);
 }

 contentPane.add(buttonPanel, BorderLayout.CENTER);


顺便说一句,您缺少} else if (command.equals("*")) {部分

关于java - '简单'2类Java计算器不接受输入或进行计算,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2470793/

10-13 09:12
查看更多