通过Java编写这个计算器,主要是用来学习JFrame容器和网格布局的。
学习JFrame的博客,感谢博主分享。 java计算器实例中,本博客共有两个版本。
1.0版本:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*
* 以下的方法调用前都没有添加对象名,创建对象后,对象会自动获取这些初始值
*/
class GridFrame extends JFrame{
//定义面板,并设置为网格布局,4行4列,组件水平、垂直间距均为3
JPanel p = new JPanel(new GridLayout(4, 4, 3, 3));
//定义文本框
JTextField t = new JTextField();
//JTextArea t = new JTextArea();
//定义字符串数组,为按钮的显示文本赋值
String str[] = {"7","8","9","/","4","5","6","*","1","2","3","-",".","0","=","+"};
// JButton equ;
public GridFrame(String s) {
//为窗体名称赋值
super(s);
setLayout(new BorderLayout());//定义窗体布局为边界布局
JButton btn[];//声明按钮数组
btn = new JButton[str.length];//创建按钮数组
//循环定义按钮,并添加到面板中
for(int i = 0; i < str.length; i ++) {
// if(i == 14) {
// equ = new JButton("=");
// p.add(equ);
// continue;
// }
btn[i] = new JButton(str[i]);
p.add(btn[i]);
}
//将文本框放在窗体的NORTH位置
getContentPane().add(t,BorderLayout.NORTH);
//将面板放在窗体的中心位置
getContentPane().add(p,BorderLayout.CENTER);
//设置背景颜色
p.setBackground(Color.PINK);
//设置窗体属性
setVisible(true);//设置窗体可见
//setResizable(false);设置窗体是否可以调整大小,默认是可以的
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置通过关闭按钮可关闭
setLocationRelativeTo(null);//让窗体居中显示
//为各按钮添加事件处理(不包含等于号)
for(int i = 0; i < str.length; i ++) {
if(i == 14)
continue;
Text(btn[i]);
}
//为“=”号添加事件处理
btn[14].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
t.setText(t.getText()+btn[14].getText());
if(t.getText().contains("+")) {
StringTokenizer st1 = new StringTokenizer(t.getText(),"+");
double d1,d2 = 0;
d1 = Double.parseDouble(st1.nextToken());
while(st1.hasMoreTokens()) {
StringTokenizer st2 = new StringTokenizer(st1.nextToken(),"=");
d2 = Double.parseDouble(st2.nextToken());
}
t.setText(t.getText()+(d1+d2));
}
else if(t.getText().contains("-")){
StringTokenizer st1 = new StringTokenizer(t.getText(),"-");
double d1,d2 = 0;
d1 = Double.parseDouble(st1.nextToken());
while(st1.hasMoreTokens()) {
StringTokenizer st2 = new StringTokenizer(st1.nextToken(),"=");
d2 = Double.parseDouble(st2.nextToken());
}
t.setText(t.getText()+(d1-d2));
}
else if(t.getText().contains("*")){
StringTokenizer st1 = new StringTokenizer(t.getText(),"*");
double d1,d2 = 0;
d1 = Double.parseDouble(st1.nextToken());
while(st1.hasMoreTokens()) {
StringTokenizer st2 = new StringTokenizer(st1.nextToken(),"=");
d2 = Double.pars