java 在java中制作计算器,如何只允许数字输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15756417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:45:29  来源:igfitidea点击:

Making a calculator in java, how to allow numeric inputs only

javaswingjframejbuttonjlabel

提问by epsilon58

IM trying to make a calculator using Java/eclipse. How do I make that only numeric values can be typed into the text area? So when i run the application it runs perfectly. All the buttons are functioning perfectly. But I would like to have it only allow number input in the text area.

IM 尝试使用 Java/eclipse 制作计算器。如何使文本区域只能输入数值?所以当我运行应用程序时,它运行得很好。所有按钮都运行良好。但我想让它只允许在文本区域输入数字。

    import java.awt.Color;
  import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.TextField;

  import javax.swing.JButton;
  import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
 import java.text.ParseException; 
  import java.util.Scanner;

   public class calculator_gui<reutrn> implements ActionListener {

JFrame frame = new JFrame("Calculator");
JPanel Panel = new JPanel (new java.awt.FlowLayout());

JTextArea text = new JTextArea(1,20);
JButton but1= new JButton("1");
JButton but2= new JButton("2");
JButton but3= new JButton("3");
JButton but4= new JButton("4");
JButton but5= new JButton("5");
JButton but6= new JButton("6");
JButton but7= new JButton("7");
JButton but8= new JButton("8");
JButton but9= new JButton("9");
JButton but0= new JButton("0");


JButton butadd= new JButton("+");
JButton butsub= new JButton("-");
JButton butmulti= new JButton("*"); 
JButton butdiv= new JButton("/");
JButton buteq= new JButton("=");
JButton butclear= new JButton("C");

Double number1,number2,result;
int addc=0,subc=0,multic=0,divc=0;



public void gui(){

    Panel.setLayout(FlowLayout());
    frame.setVisible(true);
    frame.setBounds(100, 100, 450, 285);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     //  frame.setResizable(false);

    frame.add(Panel);
    Panel.setBackground(Color.green);

    Panel.add(text);
    text.setBounds(10, 32, 361, 29);



    Panel.add(but1);
    but1.setBackground(Color.red);
    but1.setBounds(10, 81, 89, 23);

    Panel.add(but2);
    but2.setBounds(126, 81, 89, 23);

    Panel.add(but3);
    but3.setBounds(225, 81, 89, 23);

    Panel.add(but4);
    but4.setBounds(10, 115, 89, 23);

    Panel.add(but5);
    but5.setBounds(126, 115, 89, 23);

    Panel.add(but6);
    but6.setBounds(225, 115, 89, 23);

    Panel.add(but7);
    but7.setBounds(10, 149, 89, 23);

    Panel.add(but8);
    but8.setBounds(126, 149, 89, 23);

    Panel.add(but9);
    but9.setBounds(225, 149, 89, 23);

    Panel.add(but0);
    but0.setBounds(126, 183, 89, 23);

    Panel.add(butadd);
    butadd.setBounds(324, 81, 89, 23);

    Panel.add(butsub);
    butsub.setBounds(324, 115, 89, 23);

    Panel.add(butmulti);
    butmulti.setBounds(324, 183, 89, 23);

    Panel.add(butdiv);
    butdiv.setBounds(324, 149, 89, 23);

    Panel.add(buteq);
    buteq.setBounds(225, 183, 89, 23);

    Panel.add(butclear);
    butclear.setBounds(10, 183, 89, 23);





    but1.addActionListener(this);
    but2.addActionListener(this);
    but3.addActionListener(this);
    but4.addActionListener(this);
    but5.addActionListener(this);
    but6.addActionListener(this);
    but7.addActionListener(this);
    but8.addActionListener(this);
    but9.addActionListener(this);
    but0.addActionListener(this);
    butadd.addActionListener(this);
    butsub.addActionListener(this);
    butmulti.addActionListener(this);
    butdiv.addActionListener(this);
    buteq.addActionListener(this);
    butclear.addActionListener(this);






}

private LayoutManager FlowLayout() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void actionPerformed(ActionEvent e){

  Object source = e.getSource();

  if(source==butclear){

      number1=0.0;
      number2=0.0;
      text.setText(null);

  }


  if(source==but1){  
       text.append("1");        

  }


  if(source==but2){  
       text.append("2");        

  }

  if(source==but3){  
       text.append("3");        

  }

  if(source==but4){  
       text.append("4");        

  }

  if(source==but5){  
       text.append("5");        

  }

  if(source==but6){  
       text.append("6");        

  }

  if(source==but7){  
       text.append("7");        

  }

  if(source==but8){  
       text.append("8");        

  }

  if(source==but9){  
       text.append("9");        

  }

  if(source==but0){  
       text.append("0");        

  }
  if(source==butadd){
      number1=number_reader();
      text.setText("");
      addc=1;
      subc=0;
      multic=0;
      divc=0;


  }

  if(source==butsub){
      number1=number_reader();
      text.setText("");
      addc=0;
      subc=1;
      multic=0;
      divc=0;


  }
  if(source==butmulti){
      number1=number_reader();
      text.setText("");
      addc=0;
      subc=0;
      multic=1;
      divc=0;


  }
  if(source==butdiv){
      number1=number_reader();
      text.setText("");
      addc=0;
      subc=0;
      multic=0;
      divc=1;


  }



  if(source==buteq){

      number2=number_reader();
      if(addc>0){
          result=number1+number2;
          text.setText(Double.toString(result));

      }

  if(subc>0){
      result=number1-number2;
      text.setText(Double.toString(result));          
  }

  if(multic>0){
      result=number1*number2;
      text.setText(Double.toString(result));

  }




    }







     if(divc>0){
      result=number1/number2;
      text.setText(Double.toString(result));

           }


       }




public double number_reader(){
    Double num1;
    String s;
    s=text.getText();
    num1=Double.valueOf(s);

    return  num1;


        }




      }

回答by Eric Jablow

There are a number of things you can do.

您可以做很多事情。

  • Set an javax.swing.InputVerifieron your text area. This will keep people from tabbing out if they type something illegal. It probably isn't enough.
  • Set a custom Documentfor the JTextAreain its constructor. Use a subclass you write of PlainDocument, where you override its insertTextmethod and reject non-numbers. This will take care of both typing and of cut-and-paste.
  • javax.swing.InputVerifier在您的文本区域设置一个。这将防止人们在输入非法内容时被打断。这可能还不够。
  • 在其构造函数中Document为设置自定义JTextArea。使用您编写的子类PlainDocument,您可以在其中覆盖其insertText方法并拒绝非数字。这将处理打字和剪切和粘贴。

You will do better in your next attempt if you do not have one giant actionPerformedmethod for all the number and operation buttons. Instead, give each button a subclass of AbstractAction. The number buttons can share instances of one class.

如果actionPerformed所有数字和操作按钮都没有一个巨大的方法,那么您在下一次尝试中会做得更好。相反,给每个按钮一个AbstractAction. 数字按钮可以共享一个类的实例。

JComponents, which include JButtons, can have client properties, so you can write code like

JComponents,包括JButtons,可以有客户端属性,所以你可以写代码像

JButton but1= new JButton("1");
but1.setClientProperty("digit", "1");  // Why a string? 
    // Suppose you have a switch to use hexadecimals?

and then the action listener, which has access to the pressed button, can just call getClientProperty("digit")on it to find out what digit the user has chosen. For a small investment, you save a lot of repetitious code.

然后可以访问按下按钮的动作侦听器可以调用getClientProperty("digit")它来找出用户选择的数字。只需少量投资,您就可以节省大量重复代码。

Finally, learn the model-view-controller architecture, or MVC. Don't do your manipulations directly on the text area. Without RFC, you will have many problems adding more operations, or switching to a RPN calculator.

最后,学习模型-视图-控制器架构,或MVC. 不要直接在文本区域上进行操作。如果没有 RFC,您将在添加更多操作或切换到 RPN 计算器时遇到很多问题。

  1. Create a Model: This has objects for the accumulator and the new operand.
  2. Create a View: The Swing setup.
  3. Create a Controller: The objects that do the work. Your actions should be requests of the controller to do something. The controller should do it to the model, and then the model or the controller should refresh the view.
  1. 创建模型:它具有累加器和新操作数的对象。
  2. 创建视图:Swing 设置。
  3. 创建控制器:完成工作的对象。您的操作应该是控制器请求做某事。控制器应该对模型进行操作,然后模型或控制器应该刷新视图。

Also, your calculator class name is a bit weird. The name calculator_gui<reutrn>makes no sense; why a generic? Why violate Java standards? Just call it Calculator.

另外,你的计算器类名有点奇怪。这个名字calculator_gui<reutrn>毫无意义;为什么是泛型?为什么要违反 Java 标准?就叫它Calculator

Added

添加

The poster wants me to show how to turn the button creation coe into a loop. So, replace the ten lines:

海报要我展示如何将按钮创建 coe 变成一个循环。因此,替换十行:

JButton but1= new JButton("1");
JButton but2= new JButton("2");
JButton but3= new JButton("3");
JButton but4= new JButton("4");
JButton but5= new JButton("5");
JButton but6= new JButton("6");
JButton but7= new JButton("7");
JButton but8= new JButton("8");
JButton but9= new JButton("9");
JButton but0= new JButton("0");

into:

进入:

JButton[] digitButton = new JButton[10];  // digitButton is an arry of JButtons,
                                          // Initialized to nulls.
for(final int i = 0; i < 10; i++) {
    digitButton[i] = new JButton(Integer.toString(i));  // Convert 0 to "0", etc.
                                                        // Then make a button.  
}

Now, give each button its own action listener instead of having the main class have one for all.

现在,为每个按钮提供自己的动作侦听器,而不是让主类拥有一个。

回答by anshulankush

Just put a condition:

只说一个条件:

if ((text.contains("[a-zA-Z]+") == false){
//error
}

else{
//do your computation.
}

or

或者

if ((text.contains("[0-9]*") == true){
//your code    
}