这弄个输入框,挨个添加按钮。
后台弄几个变量,点击按钮给变量赋值再计算就可以了呀。
package com.huawei.test; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import java.util.regex.*; import javax.swing.*; public class Cal extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 1L; JTextField jtf = new JTextField(); public Cal() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); add(jtf, BorderLayout.NORTH); jtf.setEditable(false); JPanel jp = new JPanel(); List<String> list = new ArrayList<String>(20); List<String> list2 = new ArrayList<String>(Arrays.asList("+", "C", "-", "退格", "*", "1/x", "+/-", ".", "/", "=")); for(int i = 1; i < 10; i++) { list.add(i+""); if(i % 3 == 0) { list.addAll(list2.subList(0, 2)); list2.remove(0); list2.remove(0); } } list.add("0"); list.addAll(list2); jp.setLayout(new GridLayout(4, 5)); for(String str : list) { JButton btn = new JButton(str); btn.addActionListener(this); jp.add(btn); } add(jp, BorderLayout.CENTER); pack(); setLocation(200, 400); setResizable(false); } static String preTxt = null; @Override public void actionPerformed(ActionEvent e) { String btnTxt = ((JButton)e.getSource()).getText(); if("C".equals(btnTxt)) { jtf.setText(""); } else if("1/x".equals(btnTxt)) { double num = 0; try { num = Double.parseDouble(jtf.getText()); } catch (Exception e2) { System.out.println(e2.getMessage()); } jtf.setText(1/num+""); } else if("退格".equals(btnTxt)) { String content = jtf.getText(); if(content.length()>0) { content = content.substring(0, content.length()-1); } jtf.setText(content); } else if("+/-".equals(btnTxt)) { String content = jtf.getText(); if(content.startsWith("-")) { content = content.substring(1, content.length()); } else { content = "-" + content; } jtf.setText(content); } else if("=".equals(btnTxt)) { String content = jtf.getText(); content = getByRegex(content); jtf.setText(content); } else if(!"=".equals(preTxt)){ jtf.setText(jtf.getText()+btnTxt); } else { jtf.setText(btnTxt); } preTxt = btnTxt; } private static String calc(String content, String regex) { String pattern = regex; Pattern r = (pattern); Matcher m = r.matcher(content); if (m.find( )) { int a = Integer.parseInt(m.group(1)); int b = Integer.parseInt(m.group(3)); int res=0; if("*".equals(m.group(2))) { res = a*b; }else if("/".equals(m.group(2))) { res = a/b; }else if("+".equals(m.group(2))) { res = a+b; }else if("-".equals(m.group(2))) { res = a-b; } return content.replace(m.group(), res+""); } return content; } private String getByRegex(String content) { for(String type : Arrays.asList("*", "/", "+", "-")) { content = calc(content, "(\\d+)(\\"+type+")(\\d+)"); String content2 = null; while(!content.equals(content2)) { content2 = content; content = calc(content, "(\\d+)(\\"+type+")(\\d+)"); } } return content; } public static void main(String[] args) { new Cal(); } }