Java Calculator GUI操作

时间:2012-03-01 16:37:05

标签: java

共有4个类:MainGUILogicCalculator。我难以使计算器类正确,第一个操作/计算给了我错误的答案,但下一个是正确的。我尝试为第一个和第二个数字创建另一个变量(fnumsnum),但它不起作用。我需要修改Logic类吗?

主要课程

class Main
{ 
  public static void main( String args[] )
  {
    GUI gui = new GUI();
    gui.display();
  }
}

GUI类

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

class GUI
{
  private static final int H = 400;       // Height of window pixels
  private static final int W = 500;       // Width  of window pixels

  private JLabel      theMes      = new JLabel();       // Message area
  private JTextArea   theOutput1  = new JTextArea();    // Input number area
  private JTextArea   theOutput2  = new JTextArea();    // Result area
  private JScrollPane theSP       = new JScrollPane();

  private ButtonPress onButtonPress = new ButtonPress();

  public void display()
  {
    JFrame rpc           = new JFrame();            // Window
    Container cp         = rpc.getContentPane();    // Content Pane
    Container rootWindow = (Container) rpc;         // Root Window
    cp.setLayout(null);                             // No layout manager
    rootWindow.setSize( W, H );                     // Size of Window

    String labels[] = {
        "7",  "8", "9", "", "CR", "+",
        "4",  "5", "6", "",  "=", "-",
        "1",  "2", "3", "",  "",  "*",
        "C",  "0", "", "",   "",  "/" };

    final int LABELS = labels.length;      // # Button Labels

    final int GAP   = 15;                  // Horizontal Gap

    final int HLAB  = 20;                  // Label
    final int SHLAB = GAP;
    final int EHLAB = SHLAB+HLAB;

    final int HTA1  = 30;                  // Output area 1
    final int SHTA1 = EHLAB + GAP;
    final int EHTA1 = SHTA1 + HTA1;

    final int HTA2  = 100;                 // Output area 2
    final int SHTA2 = EHTA1 + GAP;
    final int EHTA2 = SHTA2 + HTA2;

    final int HBUT  = 170;                 // Buttons
    final int SHBUT = EHTA2 + GAP;

    final int BNR  = 4,    BNC  = 6;       // number rows cols of buttons
    final int BW  = W/BNC, BH = HBUT/BNR;  // Size of landscape for button
    final int SBH = SHBUT, SBW = 7;        // Start position for buttons


    JButton buttons[] = new JButton[LABELS];

    Font font = new Font("Serif",Font.BOLD,20);      // Button font

    for ( int i=0; i<LABELS; i++ )
    {
      if ( labels[i].length() >= 1 )
      {
        buttons[i] = new JButton( labels[i] );
        final int col = i%BNC * BW, row = i/BNC * BH;
        buttons[i].setBounds( SBW+col, SBH+row, BW-20, BH-10 );
        buttons[i].addActionListener( onButtonPress );
        buttons[i].setFont( font );
        cp.add( buttons[i] );
      }
    }

    font = new Font("Serif",Font.BOLD,14);         // Font is

    theMes.setBounds( 10, SHLAB, W-25, HLAB );     // Message area
    theMes.setText( "" );                          // Blank
    theOutput1.setFont( font );                    //  Uses font 
    cp.add( theMes );                              //  Add to canvas

    theOutput1.setBounds( 10, SHTA1, W-25, HTA1 ); // Input Area
    theOutput1.setText("");                        // Blank
    theOutput1.setFont( font );                    //  Uses font 
    cp.add( theOutput1 );                          //  Add to canvas

    font = new Font("Serif",Font.BOLD,14);         // Font is

    theSP.setBounds( 10, SHTA2, W-25, HTA2 );      // Scrolling pane
    theOutput2.setText( "" );                      //  Blank
    theOutput2.setFont( font );                    //  Uses font  
    cp.add( theSP );                               //  Add to canvas
    theSP.getViewport().add( theOutput2 );         //  In TextArea
    rootWindow.setVisible( true );                 // Make visible

    theMes.setText( "Calculator" );                // Opening message
  }


  private Calculator calc = new Calculator();
  private Logic logic     = new Logic( calc );

  class ButtonPress implements ActionListener       // Listener
  {
    public void actionPerformed( ActionEvent ae )   // Interaction
    {
      String label = ae.getActionCommand();         // Button label  

      String info = logic.process( label);

      theOutput2.setText( "" );
      if ( info == null )
        theOutput2.append( "" + logic.getResult() );
      else
        theOutput2.append( info );

      theOutput1.setText( "" );
      theOutput1.append( "Number entered: " + logic.getNumber() );
    }
  }
}

逻辑课

class Logic
{
  private enum  State { FIRST_NUMBER, SUBSEQUENT_NUMBER };
  private State state = State.FIRST_NUMBER;
  private long  number = 0;
  private char  op = ' ';
  private Calculator calc = null;


  public Logic( Calculator calculator )
  {
    calc = calculator;
  }

  public String process( String button )
  {
    String info = null;
    if ( button.length() == 1 )
    {
      char c = button.charAt(0);
      if ( c >= '0' && c <= '9' )               // Digit
      {
        number = number * 10 + c-'0';           // Build number
      } else {
        switch ( c )
        {
          case 'C' : number = 0;
                     break;
          case '=' :
          case '+' : case '-' :
          case '*' : case '/' :
            switch ( state )
            {
              case FIRST_NUMBER:
                calc.setValue( number );
                state = State.SUBSEQUENT_NUMBER;
                break;
              case SUBSEQUENT_NUMBER:
                if ( op != '=' )
                  calc.evaluate( op, number );
                break;
            }
            op = c;  number = 0;
            break;
        }
      }
    } else {
      if ( button.equals( "CR" ) )               // Clear Result
      {
        calc.reset(); number = 0; state = State.FIRST_NUMBER;
      }
    }

    return info;
  }

  public long getResult()
  {
    return calc.getValue();
  }

  public long getNumber()
  {
    return number;
  }
}

计算器类

class Calculator
{
//Evaluate an arithmetic operation on the stored result
// E.g evaluate( '+',9) would add 9 to the stored result
// evaluate( '/',3) would divide the stored result
// by 3
// actions are '+'. '-', '*', '/'
//Note: if the operation is
// evaluate( '/',0 ) the result returned should be 0


long value;


public void evaluate( char action, long number )
 {

     if (action == '+'){
      value += Float.valueOf(number).floatValue();


     }

    else if (action == '-'){
      value -= Float.valueOf(number).floatValue();

    }

    else if (action == '*'){
      value *= Float.valueOf(number).floatValue();

    }

    else if (action == '/'){
      value /= Float.valueOf(number).floatValue();

    }

}
//Return the stored result
public long getValue()
   {
    return value;
    }

//Set the stored result to number
public void setValue( long number )
{

}

//Reset the stored number to 0
public void reset()
{
       if ( value != 0) value = 0;
    }
}

3 个答案:

答案 0 :(得分:3)

问题是你实际上没有在setValue方法中设置值:

//Set the stored result to number
public void setValue( long number )
{
    this.value = number;
}

那应该解决它。

答案 1 :(得分:2)

由于已经指出了答案,这里有一些关于代码的一般指示:

  1. 你已经按区域分手了,这很好。
  2. 您需要在rpc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);中添加GUI,否则您的计算器类将连续运行,甚至 后面的“退出”图标已关闭。
  3. 这一行:Container rootWindow = (Container) rpc;毫无意义,因为rpc已被作为容器引用。
  4. 您的一些变量名称完全是神秘的(HLABSHTA1HTA2?)。始终以恰当和描述性的方式标记事物。
  5. 您正在使用long来存储和显示您的值,但是float来执行实际数学运算。这意味着程序会生成奇怪的结果 - 例如9 / 2 = 4。另外,与您的评论相反,9 / 0 = 9223372036854775807。我建议您生成初始数字('输入数字')作为字符的stacj,并使用BigDecimal执行所有数学运算。
  6. 您故意忽略布局管理器,然后竭尽全力手动定位所有按钮/标签。不幸的是,如果调整大小,这会使您的应用程序中断。你需要做的是将你的显示分成几个(嵌套的)JPanel,每个都有适当的布局管理器。如有必要,可以使用IDE和插件来直观地设计此类系统。
  7. 您正在执行swing事件线程中的所有内容。虽然它在这里工作,但它不是最佳实践,并且可以是打破或挂起应用程序的最快方法之一。应使用SwingUtilities.invokeLater();调度所有图形内容创建和操作,包括创建主窗口。
  8. 您正在解析按钮的标签以选择要执行的操作。这并不能很好地处理国际化等问题。如果时间允许,请考虑使用Strategy Pattern来封装您的行为。你至少需要两套;一个用于将数字放在堆栈上,另一个用于执行计算。这也意味着添加新操作(如pow函数)不需要修改代码,只需添加新行为(和按钮)。
  9. 对于进一步和未来的批评,请在CodeReview上发布代码!

答案 2 :(得分:0)

package Calculator;

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

public class Carl extends JFrame {

JTextField text1 = new JTextField();
JLabel label1 = new JLabel(" ");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
JButton button5 = new JButton("5");
JButton button6 = new JButton("6");
JButton button7 = new JButton("7");
JButton button8 = new JButton("8");
JButton button9 = new JButton("9");
JButton button10 = new JButton("0");
JButton button11 = new JButton("+");
JButton button12 = new JButton("-");
JButton button13 = new JButton("*");
JButton button14 = new JButton("/");
JButton button15 = new JButton("=");
JButton button16 = new JButton("C");
JLabel blank1 = new JLabel("");
JLabel blank2 = new JLabel("");
JLabel blank3 = new JLabel("");
JLabel blank4 = new JLabel("");
Font times = new Font("Times New Roman", Font.BOLD, 18);
int operation1;
int operation2;
int operation3;
int operation4;
String n1, n2;
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();

public Carl() {
    setResizable(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Calculator");
    setSize(600, 600);
    button1.setForeground(Color.BLACK);
    button2.setForeground(Color.BLACK);
    button3.setForeground(Color.BLACK);
    button4.setForeground(Color.BLACK);
    button5.setForeground(Color.BLACK);
    button6.setForeground(Color.BLACK);
    button7.setForeground(Color.BLACK);
    button8.setForeground(Color.BLACK);
    button9.setForeground(Color.BLACK);
    button10.setForeground(Color.BLACK);
    button11.setForeground(Color.BLACK);
    button12.setForeground(Color.BLACK);
    button13.setForeground(Color.BLACK);
    button14.setForeground(Color.BLACK);
    button15.setForeground(Color.BLACK);
    button16.setForeground(Color.BLACK);
    button1.setBackground(Color.YELLOW);
    button2.setBackground(Color.YELLOW);
    button3.setBackground(Color.YELLOW);
    button4.setBackground(Color.YELLOW);
    button5.setBackground(Color.YELLOW);
    button6.setBackground(Color.YELLOW);
    button7.setBackground(Color.YELLOW);
    button8.setBackground(Color.YELLOW);
    button9.setBackground(Color.YELLOW);
    button10.setBackground(Color.YELLOW);
    button11.setBackground(Color.YELLOW);
    button12.setBackground(Color.YELLOW);
    button13.setBackground(Color.YELLOW);
    button14.setBackground(Color.YELLOW);
    button15.setBackground(Color.YELLOW);
    button16.setBackground(Color.YELLOW);
    button1.setToolTipText("one");
    button2.setToolTipText("two");
    button3.setToolTipText("three");
    button4.setToolTipText("four");
    button5.setToolTipText("five");
    button6.setToolTipText("six");
    button7.setToolTipText("seven");
    button8.setToolTipText("eight");
    button9.setToolTipText("nine");
    button10.setToolTipText("zero");
    button11.setToolTipText("addition");
    button12.setToolTipText("subtraction");
    button13.setToolTipText("multiplication");
    button14.setToolTipText("division");
    button15.setToolTipText("equal");
    button16.setToolTipText("clear");
    button1.setFont(times);
    button2.setFont(times);
    button3.setFont(times);
    button4.setFont(times);
    button5.setFont(times);
    button6.setFont(times);
    button7.setFont(times);
    button8.setFont(times);
    button9.setFont(times);
    button10.setFont(times);
    button11.setFont(times);
    button12.setFont(times);
    button13.setFont(times);
    button14.setFont(times);
    button15.setFont(times);
    button16.setFont(times);
    label1.setFont(times);
    setLayout(new BorderLayout());
    p1.setLayout(new GridLayout(6, 3, 2, 2));
    p1.add(p2, BorderLayout.CENTER);
    p1.add(label1);
    p1.add(text1);
    p1.add(blank3);
    p1.add(button7);
    p1.add(button8);
    p1.add(button9);
    p1.add(button11);
    p1.add(button4);
    p1.add(button5);
    p1.add(button6);
    p1.add(button12);
    p1.add(button1);
    p1.add(button2);
    p1.add(button3);
    p1.add(button13);
    p1.add(button10);
    p1.add(button16);
    p1.add(button15);
    p1.add(button14);
    add(p1, BorderLayout.CENTER);

    button1.addActionListener(new Listener1());
    button2.addActionListener(new Listener2());
    button3.addActionListener(new Listener3());
    button4.addActionListener(new Listener4());
    button5.addActionListener(new Listener5());
    button6.addActionListener(new Listener6());
    button7.addActionListener(new Listener7());
    button8.addActionListener(new Listener8());
    button9.addActionListener(new Listener9());
    button10.addActionListener(new Listener0());
    button11.addActionListener(new ListenerAdd());
    button12.addActionListener(new ListenerSub());
    button13.addActionListener(new ListenerMul());
    button14.addActionListener(new ListenerDiv());
    button15.addActionListener(new ListenerEqual());
    button16.addActionListener(new ListenerClear());
    setVisible(true);

}

private class Listener1 implements ActionListener {

    public void actionPerformed(ActionEvent a) {
        n1 = text1.getText();
        text1.setText(n1 + "1");
    }
}

private class Listener2 implements ActionListener {

    public void actionPerformed(ActionEvent b) {
        n1 = text1.getText();
        text1.setText(n1 + "2");
    }
}

private class Listener3 implements ActionListener {

    public void actionPerformed(ActionEvent c) {
        n1 = text1.getText();
        text1.setText(n1 + "3");
    }
}

private class Listener4 implements ActionListener {

    public void actionPerformed(ActionEvent d) {
        n1 = text1.getText();
        text1.setText(n1 + "4");
    }
}

private class Listener5 implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        n1 = text1.getText();
        text1.setText(n1 + "5");
    }
}

private class Listener6 implements ActionListener {

    public void actionPerformed(ActionEvent f) {
        n1 = text1.getText();
        text1.setText(n1 + "6");
    }
}

private class Listener7 implements ActionListener {

    public void actionPerformed(ActionEvent g) {
        n1 = text1.getText();
        text1.setText(n1 + "7");
    }
}

private class Listener8 implements ActionListener {

    public void actionPerformed(ActionEvent h) {
        n1 = text1.getText();
        text1.setText(n1 + "8");
    }
}

private class Listener9 implements ActionListener {

    public void actionPerformed(ActionEvent i) {
        n1 = text1.getText();
        text1.setText(n1 + "9");
    }
}

private class Listener0 implements ActionListener {

    public void actionPerformed(ActionEvent j) {
        n1 = text1.getText();
        text1.setText(n1 + "0");
    }
}

private class ListenerAdd implements ActionListener {

    public void actionPerformed(ActionEvent k) {
        n2 = text1.getText();
        operation1 = 1;
        text1.setText("");
    }
}

private class ListenerSub implements ActionListener {

    public void actionPerformed(ActionEvent l) {
        n2 = text1.getText();
        operation2 = 2;
        text1.setText("");
    }
}

private class ListenerMul implements ActionListener {

    public void actionPerformed(ActionEvent m) {
        n2 = text1.getText();
        operation3 = 3;
        text1.setText("");
    }
}

private class ListenerDiv implements ActionListener {

    public void actionPerformed(ActionEvent n) {
        n2 = text1.getText();
        operation4 = 4;
        text1.setText("");
    }
}

private class ListenerEqual implements ActionListener {

    public void actionPerformed(ActionEvent o) {
        if (operation1 == 1) {
            int a = Integer.parseInt(n2);
            int b = Integer.parseInt(text1.getText());
            int sum = (a + b);
            String sum1 = Integer.toString(sum);
            text1.setText(sum1);
        } else {
            text1.getText();
        }
        if (operation2 == 2) {
            int a = Integer.parseInt(n2);
            int b = Integer.parseInt(text1.getText());
            int dif = (a - b);
            String dif1 = Integer.toString(dif);
            text1.setText(dif1);
        } else {
            text1.getText();
        }
        if (operation3 == 3) {
            int a = Integer.parseInt(n2);
            int b = Integer.parseInt(text1.getText());
            int product = (a * b);
            String product1 = Integer.toString(product);
            text1.setText(product1);
        } else {
            text1.getText();
        }
        if (operation4 == 4) {
            double a = Double.parseDouble(n2);
            double b = Double.parseDouble(text1.getText());
            double quo = (a / b);
            String quo1 = Double.toString(quo);
            text1.setText(quo1);
        } else {
            text1.getText();
        }
    }
}

private class ListenerClear implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent p) {
        text1.setText("");
    }
}

public static void main(String[] args) {
    Carl frame = new Carl();
}
}

使用此代码..