Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize graphical Interface Calculator with Java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to achieve graphical interface calculator with Java". In daily operation, I believe that many people have doubts about how to achieve graphical interface calculator with Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to achieve graphical interface calculator with Java". Next, please follow the editor to study!

Code:

Import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Stack Public class Calculator extends JFrame implements ActionListener {private final String [] ButtonNames = {"(", ")", "←", "C", "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "0", "=", "/"} Private JTextField DisplayBox = new JTextField ("0.0"); private JTextField Cache = new JTextField (""); private JButton [] Buttons = new JButton [ButtonNames.length]; public Calculator () {super (); setTitle (Calculator); init (); setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); setBounds (100,100,400,600); setResizable (false) / / window cannot be resized setVisible (true);} private void init () {/ / complete layout and define listener DisplayBox.setHorizontalAlignment (JTextField.RIGHT); / / text box right-aligned DisplayBox.setFont (new Font ("DIN", Font.BOLD, 30)) / / DIN: a common numeric font Cache.setFont (new Font ("DIN", Font.BOLD, 30); GridBagLayout gridBagLayout = new GridBagLayout (); / / Grid package layout GridBagConstraints gridBagConstraints = new GridBagConstraints (); gridBagConstraints.fill = GridBagConstraints.BOTH; / / this method is used to set gridBagConstraints.weightx = 1 if the area in which the component is located is larger than the component itself / / to make the maximum size of the component gridBagConstraints.weighty = 1; setLayout (gridBagLayout); gridBagConstraints.gridx = 0; / / the starting position of the cache is (0Power0), occupying 4 squares horizontally and gridBagConstraints.gridy = 0 vertically; gridBagConstraints.gridwidth = 4; gridBagConstraints.gridheight = 1; gridBagLayout.setConstraints (Cache, gridBagConstraints); this.add (Cache) GridBagConstraints.gridx = 0; / / text box start position is (0jue 0), horizontal occupies 4 squares, vertical 2 squares gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 4; gridBagConstraints.gridheight = 2; gridBagLayout.setConstraints (DisplayBox, gridBagConstraints); this.add (DisplayBox); gridBagConstraints.gridy = 3; / / button start position is (0Magin3) gridBagConstraints.gridwidth = 1 / / each button occupies 1 grid gridBagConstraints.gridheight = 1; for (int I = 0; I

< ButtonNames.length; i++) { Buttons[i] = new JButton(ButtonNames[i]); } int n = 0; //记录每一行输出的按钮数,满4换行 for (int i = 0; i < Buttons.length; i++) { gridBagLayout.setConstraints(Buttons[i], gridBagConstraints); this.add(Buttons[i]); n++; if (n == 4) { gridBagConstraints.gridx = 0; gridBagConstraints.gridy++; n = 0; } else { gridBagConstraints.gridx++; } } for (int i = 0; i < Buttons.length; i++) { //事件监听器 Buttons[i].addActionListener(this); } } @Override public void actionPerformed(ActionEvent e) { //对事件的处理 String str; String value = e.getActionCommand(); //获取按钮的值 char v = value.charAt(0); switch (v) { case 'C': DisplayBox.setText("0.0"); break; case '←': DeleteOne(); break; case '=': String string = DisplayBox.getText(); Cache.setText(string + "="); if (isTrue(string)) { //若格式正确 str = retureResult(); DisplayBox.setText(str); } else { DisplayBox.setText("输入格式不合法"); } break; default: AddOne(value); break; } } private void DeleteOne() { //删除一个字符 String str; str = DisplayBox.getText(); if (str.length() == 1) { DisplayBox.setText("0.0"); } else if(!str.equals("0.0")) { str = str.substring(0, str.length() - 1); //去掉最后一个元素 DisplayBox.setText(str); } } private void AddOne(String value) { //增加一个字符 String str; str = DisplayBox.getText(); if (str.equals("0.0")) { //第一次输入 DisplayBox.setText(value); } else { str = str + value; DisplayBox.setText(str); } } private String retureResult() { //对输入的式子进行运算;基本方法:逆波兰法,中缀转后缀 String string = DisplayBox.getText(); String[] Midfix = breakDown(string); //中缀表达式的数组 String[] suffix = Conversion(Midfix); //得到后缀表达式 String result = Calculation(suffix); //计算后缀表达式结果 return result; } private String Calculation(String[] suffix) { Stack stack = new Stack(); String symbols = "+-*/"; //转换为后缀表达式的式子只会有 +-*/ 符号不会有 () for (int i = 0; i < suffix.length; i++) { if (suffix[i] == null) { //suffix后面可能出现null 故对其筛选不进行下列的操作 continue; } if (symbols.indexOf(suffix[i]) >

= 0) double top1; double top2; double top; switch (suffix [I]) {case "+": top1 = Double.parseDouble (stack.pop ()) / / take the top of the stack and convert it to double top2 = Double.parseDouble (stack.pop ()); top = top2 + top1; stack.push (String.valueOf (top)); / / convert top to String stack break Case "-": top1 = Double.parseDouble (stack.pop ()); top2 = Double.parseDouble (stack.pop ()); top = top2-top1; stack.push (String.valueOf (top)); break Case "*": top1 = Double.parseDouble (stack.pop ()); top2 = Double.parseDouble (stack.pop ()); top = top2 * top1; stack.push (String.valueOf (top)); break Case "/": top1 = Double.parseDouble (stack.pop ()); top2 = Double.parseDouble (stack.pop ()); if (top1 = = 0) {the divisor appears 0 "during the return" operation } top = top2 / top1; stack.push (String.valueOf (top)); break;}} else {/ / direct stack stack.push for numbers (suffix [I]) }} String result = stack.pop (); return result;} private String [] breakDown (String string) {/ / decompose (23.14) + 9 into (23.14) + 9 to facilitate subsequent calculation of String [] split = string.split (""); String DigitString = "0123456789."; String afterSplit = ""; for (int I = 0; I)

< split.length; i++) { //将 2+3.14 变成 2,+,3.14 便于拆分 if (DigitString.indexOf(split[i]) >

= 0) {afterSplit = afterSplit + split [I];} else if (afterSplit.equals ("") & & DigitString.indexOf (split [I])

< 0) { //第一个为符号时只在后面加。 afterSplit = afterSplit + split[i] + ","; } else { //为 () 或 =-*/ 在其两侧加上 , afterSplit = afterSplit + "," + split[i] + ","; } } afterSplit = afterSplit.replace(",,", ","); //避免(2+3)+2产生……3,),,+,2 split = afterSplit.split(","); //产生的字符串数组中只会含+-*/()整数和小数 return split; } private String[] Conversion(String[] strings) { //中缀转后缀 String[] suffix = new String[strings.length]; //后缀表达式 int n = 0; //suffix的下标 Stack stack = new Stack(); String first = "*/"; String symbols = "+-*/()"; for (int i = 0; i < strings.length; i++) { if(symbols.indexOf(strings[i]) >

= 0) {/ / when if (stack.empty ()) {stack.push (strings [I]) } else {/ / Stack is not empty if (first.indexOf (strings [I]) > = 0 | | strings.equals ("(")) {/ / is + / (directly stacks stack.push (strings [I])) } else if (strings.equals (")") {String top = stack.peek (); while (! top.equals ("(")) {top = stack.pop (); suffix [n] = top Else else {/ / symbol is +-if (first.indexOf (stack.peek ()

< 0) { //当栈顶不为为 */ 直接入栈 stack.push(strings[i]); } else { while (!stack.empty() && first.indexOf(stack.peek()) >

= 0) / / when the stack top operator is earlier than the current operator, the stack top operator is lower than or the stack is empty {String s = stack.pop (); suffix [n] = s; n stack + } stack.push (strings [I]); / / current operator stack} else {/ / the number directly becomes part of the suffix suffix [n] = strings [I] While (! stack.empty ()) {/ / clear the remaining symbols in the stack String s = stack.pop (); suffix [n] = s; nymphs;} return suffix } private boolean isTrue (String str) {if (! BracketMatching (str)) {/ / parentheses match return false;} if (! OperatorIsTrue (str)) {/ / symbol format correct return false;} return true } private boolean OperatorIsTrue (String string) {/ / Operand number = Operand + 1 String [] split = breakDown (string); String symblos = "+-* /"; String bracket = "()"; int NumberOfDigits = 0; int NumberOfSymblos = 0; for (int I = 0; I)

< split.length; i++) { if(symblos.indexOf(split[i]) >

= 0) {NumberOfSymblos++;} else if (bracket.indexOf (split [I]) < 0) {/ / not parentheses, not an operator must be the operator NumberOfDigits++;}} if (NumberOfDigits! = NumberOfSymblos+ 1) {return false;} return true } private boolean BracketMatching (String string) {/ / determine whether the parentheses match, otherwise an error will be reported: char [] split = string.toCharArray (); Stack stack = new Stack (); for (int I = 0; I < split.length; I +) {if (split [I] = ='(') {stack.push (split [I])) } else if (! stack.empty () & & split [I] = =')) {stack.pop ();} else if (stack.empty () & & split [I] = =')') {return false;}} if (! stack.empty ()) {return false;} return true } public static void main (String [] args) {Calculator calculator = new Calculator ();}} at this point, the study on "how to implement a graphical interface calculator with Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report