计算器应用程序:在输入数字之前阻止用户输入操作员

时间:2014-08-22 13:10:07

标签: java swing

我有这个Java Swing应用程序,一个简单的计算器,我不知道如何不先添加操作。它允许我在插入数字之前添加操作,这对我来说是个大问题。谁能告诉我如何解决这个问题?

public class DetailsPanel extends JPanel{
  private JTextField display;
  private String buttonsLabel;
  int labelCounter = 0;
  private final GridBagLayout layout;
  private final GridBagConstraints gc;
  private JButton[] numberButton, oppButtons;
  private String oppLabel[] = {"C","+/-","*","/","-","+","=",".","sqrt","sqr","min","max"}, lastOperator, lastNumber;
  private Boolean operation = false, number = false, isSet = false, operatorExist = false, lastNumberExist = false;     

  //[0]=gridx,[1]=gridy,[2]=gridwidth,[3]=gridhewight
  private final int[][] grid = new int[][] {
    {0,6,2,1}, //0
    {0,5,1,1}, //1
    {1,5,1,1}, //2
    {2,5,1,1}, //3
    {0,4,1,1}, //4
    {1,4,1,1}, //5
    {2,4,1,1}, //6
    {0,3,1,1}, //7
    {1,3,1,1}, //8
    {2,3,1,1}  //9
  };
  private final int[][] grid2 = new int[][] {
    /* C */{0,2,1,1},    
    /* +/- */{1,2,1,1},
    /* * */{2,2,1,1},
    /* / */{3,2,1,1},
    /* - */{3,3,1,1},
    /* + */{3,4,1,1},
    /* = */{3,5,1,2},
    /* . */{2,6,1,1},
    /* sqrt */ {0,7,1,1},
    /*sqr*/{1,7,1,1},
    /*min*/{2,7,1,1},
    /*max*/{3,7,1,1}
  };    
  public DetailsPanel(){
    //JOptionPane.showMessageDialog(null, 12.2 % 1 != 0);
    Dimension size = getPreferredSize();
    size.width = 224;
    size.height = 324;
    setPreferredSize(size);

    //Dysplay 
    display = new JTextField("0");
    display.setEditable(false);
    display.setBackground(Color.WHITE);

    //Set layout
    layout = new GridBagLayout();
    layout.columnWidths = new int[] {40,40,40,40};
    layout.rowHeights = new int[] {40,40,40,40,40,40,40,40};
    setLayout(layout);

    gc = new GridBagConstraints();

    //ADD Dysplay
    gc.gridx = 0;
    gc.gridy = 0;
    gc.gridwidth = 4;
    gc.gridheight = 2;
    gc.fill = GridBagConstraints.BOTH;
    add(display, gc);  
    numberButton = new JButton[10];

    //Start adding buttons
    for(int i = 0; i<numberButton.length;i++){
      numberButton[i] = new JButton("" +i); 
      gc.gridx = grid[i][0];
      gc.gridy = grid[i][1];
      gc.gridwidth = grid[i][2];
      gc.gridheight = grid[i][3];
      gc.fill = GridBagConstraints.BOTH;
      add(numberButton[i], gc);
    }

    oppButtons = new JButton[12];  
    for(int i = 0; i<oppLabel.length; i++){
      oppButtons[i] = new JButton("" +oppLabel[i]); 
      gc.gridx = grid2[i][0];
      gc.gridy = grid2[i][1];
      gc.gridwidth = grid2[i][2];
      gc.gridheight = grid2[i][3];
      gc.fill = GridBagConstraints.BOTH;
      add(oppButtons[i], gc);
    }

    //Action listener Object
    HandlerClassNumbers handlerNumbers = new HandlerClassNumbers();
    HandlerClassOpperations handlerOperations = new HandlerClassOpperations();

    for (JButton numberButton1 : numberButton) {
      numberButton1.addActionListener(handlerNumbers);
    }
    for(int i = 0; i<oppLabel.length; i++){
      oppButtons[i].addActionListener(handlerOperations);
    }
  }//End of Details panel 

  //Action listener Classes start

  public class HandlerClassNumbers implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
      if(!number){
        addDysplay(e.getActionCommand(), operation);
      }
    }
  }

  public class HandlerClassOpperations implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e1) {
      switch (e1.getActionCommand()) {
        case "C":
          delete();
          break;
        case "+/-":
          display.setText(Double.toString(-1 * Double.parseDouble(display.getText())));
          if(isInt()){
            transformToInt();
          }
          break;
        case ".":
          addPoint();
          break;
        case "sqrt":
          sqrt();
          break;
        case "sqr":
          sqr();
          break;
        case "=":
          if(operatorExist)
            if(isNumeric(display.getText()))
              switch (lastOperator) {
                case "+":
                  plus();
                  reset();
                  break;
                case "-":
                  minus();
                  reset();
                  break;
                case "/":
                  div();
                  reset();
                  break;
                case "*":
                  mul();
                  reset();
                  break;
                case "max":
                  max();
                  reset();
                  break;
                case "min":
                  min();
                  reset();
                  break;
              }
            else{
              JOptionPane.showMessageDialog(null, "Numar introdus incorect!");
            }
          else{
            JOptionPane.showMessageDialog(null, "Nu a-ti adaugat o operatie!");
          }
          /////////////////Action equal end///////////////////
          break;
        default:
          if(!operatorExist){
            lastOperator = e1.getActionCommand();
            lastNumber = display.getText();
            lastNumberExist = true;
            operatorExist = true;
            delete();
            break;
      }
    }
  }
}

  //Program methods

  public void addDysplay(String number, Boolean operation){
    if(!isSet){
      isSet = true;
      display.setText(number);
    }else{
      display.setText(display.getText()+number);
    }
  }
  public void delete(){
    if(operatorExist){
      display.setText(lastOperator);
    }else
      display.setText("0");
    isSet = false;
  }
  public void reset(){
    lastOperator = null;
    lastNumber = null;
    operatorExist = false;
    lastNumberExist = false;
  }
  public void addPoint(){
    String pattern = "^[-+]?\\d+\\.{0}\\d+$";
    if(display.getText().matches(pattern)){
      display.setText(display.getText()+".");
    }else{
      if(display.getText().length() == 1){
        display.setText(display.getText()+".");
      }
    }
  }
  public Boolean isInt(){
    Double disp = Double.parseDouble(display.getText());
    return disp % 1 == 0;
  }
  public void transformToInt(){
    Double disp = Double.parseDouble(display.getText());
    display.setText(Integer.toString(disp.intValue()));
  }

  public static boolean isNumeric(String str){
    return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
  }

  ////////////////////Operation methods////////////////////

  public void plus(){
    display.setText(Double.toString(Double.parseDouble(lastNumber)+Double.parseDouble(display.getText())));
    if(isInt()){
      transformToInt();
    }
  }
  public void minus(){
    display.setText(Double.toString(Double.parseDouble(lastNumber)-Double.parseDouble(display.getText())));
    if(isInt()){
      transformToInt();
    }
  }
  public void mul(){
    display.setText(Double.toString(Double.parseDouble(lastNumber)*Double.parseDouble(display.getText())));
    if(isInt()){
      transformToInt();
    }
  }
  public void div(){
    display.setText(Double.toString(Double.parseDouble(lastNumber)/Double.parseDouble(display.getText())));
    if(isInt()){
      transformToInt();
    }
  }
  public void equal(){
    if(isInt()){
      transformToInt();
    }
  }
  public void sqrt(){
    if(Double.parseDouble(display.getText()) > 0)
      display.setText(Double.toString(Math.sqrt(Double.parseDouble(display.getText()))));
    else{
      JOptionPane.showMessageDialog(null, "sqrt(" +display.getText() + ") impossible!");
      delete();
    }
    if(isInt()){
      transformToInt();
    }
  }
  public void sqr(){
    display.setText(Double.toString(Double.parseDouble(display.getText()) * Double.parseDouble(display.getText())));
    if(isInt()){
      transformToInt();
    }
  }
  public void min(){
    String disp = display.getText();
    if(disp.compareTo(lastNumber) > 0){
      display.setText(lastNumber);
    }
    if(isInt()){
      transformToInt();
    }
  }
  public void max(){
    String disp = display.getText();
    if(disp.compareTo(lastNumber) < 0){
      display.setText(lastNumber);
    }
    if(isInt()){
      transformToInt();
    }
  }

  ////////////////////Operation methods end/////////////////

}//Ends of DetailsPanel class

0 个答案:

没有答案