用java编写一个简易的计算器代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*使用java 语言开发一个简易计算器
*
*
*/
public class TestJsq extends JFrame implements ActionListener, KeyListener { private JTextField jtf;
private JButton jb_bk, jb_ce, jb_c;
private String xs = "";
private double sum = 0;
private int fh;
public static void main(String[] args) {
new TestJsq().creatCUI();
}
public void creatCUI() {
JFrame jf = new JFrame();
jf.setTitle("计算器");
jtf = new JTextField("0.");
jtf.setHorizontalAlignment(JTextField.RIGHT);
jf.add(jtf, BorderLayout.NORTH);
JPanel jp_main = new JPanel(new BorderLayout());
jf.add(jp_main);
JPanel jp1 = new JPanel(new GridLayout(1, 3, 1, 1));
jb_bk = new JButton("Backspace");
jb_bk.setForeground(Color.RED);
jb_bk.addActionListener(this);
jb_ce = new JButton("CE");
jb_ce.setForeground(Color.RED);
jb_ce.addActionListener(this);
jb_c = new JButton("C");
jb_c.setForeground(Color.RED);
jb_c.addActionListener(this);
jp1.add(jb_bk);
jp1.add(jb_ce);
jp1.add(jb_c);
jp_main.add(jp1, BorderLayout.NORTH);
JPanel jp2 = new JPanel(new GridLayout(4, 5, 1, 1));
String str[] = { "7", "8", "9", "/", "sqrt", "4", "5", "6", "*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
for (int i = 0; i < 20; i++) {
JButton jb = new JButton(str[i]);
jb.addActionListener(this);
jb.setForeground(Color.blue);
if (i == 3 || i == 8 || i == 13 || i == 18 || i == 19) {
jb.setForeground(Color.RED);
}
jp2.add(jb);
}
jp_main.add(jp2, BorderLayout.CENTER);
jf.setResizable(false);
jf.setBounds(50, 50, 350, 350);
jf.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("CE") || s.equals("C")) {
xs = "";
jtf.setText("0.");
} else if (s.equals("Backspace")) {
String str = xs.substring(0, xs.length() - 1);
xs = str;
jtf.setText(xs);
} else if (s.equals("7") || s.equals("8") || s.equals("9")
|| s.equals("4") || s.equals("5") || s.equals("6")
|| s.equals("1") || s.equals("2") || s.equals("3")
|| s.equals("0") || s.equals(".")) {
xs = xs + s;