Java利用Swing编写普通计算器
自己尝试敲的,可以自行优化代码,或者添加内容
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame {
//顶级窗口
private static JFrame jf ;
//容器
private static JPanel jp ;
//按钮
private static JButton[] buttons = new JButton[16];
//文本域
private static JTextArea jta;
//获取子字符串
private static String [] strs;//第一个数
//结果为Double类型
private static Double result;//结果
//判断加减乘除符号
private static String x = null;
//实现窗口
public static void setFrame()
{
//实例化一个顶级窗口
jf = new JFrame("计算器");
//设置窗体大小
jf.setLocation(200,200);
jf.setSize(300,500);
//实例化一个文本域 3行 15列
jta = new JTextArea(3,15);
jta.setEditable(false);//设置为不可编辑
//实例化一个容器,设置网格布局->4行4列
jp = new JPanel();
jp.setLayout(new GridLayout(4,4));
//jp放入按钮
int flag = 9;//用于设置按钮的名字
for (int i = 0 ; i < 16 ; i++)
{
if (i == 13) jp.add(buttons[i] = new JButton("0"));
if (i == 3) jp.add(buttons[i] = new JButton("×"));
if (i == 7) jp.add(buttons[i] = new JButton("÷"));
if (i == 11) jp.add(buttons[i] = new JButton("-"));
if (i == 14) jp.add(buttons[i] = new JButton("+"));
if (i == 15) jp.add(buttons[i] = new JButton("="));
if (i == 12) jp.add(buttons[i] = new JButton("清空"));
if (i >= 0 && i <= 2 ||
i >= 4 && i <= 6 ||
i >= 8 && i <= 10)
{
jp.add(buttons[i] = new JButton(""+flag));
flag--;
}
}
//添加监听
for ( JButton j : buttons)
{
j.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jta.append(e.getActionCommand());
//若按了其他符号,则记录符号
if (("+").equals(e.getActionCommand()) ||
("-").equals(e.getActionCommand()) ||
("×").equals(e.getActionCommand()) ||
("÷").equals(e.getActionCommand())
)
{
x = e.getActionCommand();
}
//若按了"清空",把文本域的内容设置为空
if ("清空".equals(e.getActionCommand()))
{
jta.setText("");
}
//若按了"=",先拆分
if(("=").equals(e.getActionCommand()))
{
//获取文本域的字符串
String temp = jta.getText();
//将文本域的字符串按正则表达式进行拆分
strs = temp.split("[^\\d]");
//判断符号,并进行计算
if ("+".equals(x))
{
result = Double.parseDouble(strs[0]) + Double.parseDouble(strs[1]);
}
if ("-".equals(x))
{
result = Double.parseDouble(strs[0]) - Double.parseDouble(strs[1]);
}
if ("×".equals(x))
{
result = Double.parseDouble(strs[0]) * Double.parseDouble(strs[1]);
}
if ("÷".equals(x))
{
result = Double.parseDouble(strs[0]) / Double.parseDouble(strs[1]);
}
jta.append(""+result);//把结果追加到字符串尾部
}
}
});
}
//添加组件
jf.setLayout(new BorderLayout());
jf.add(jta,BorderLayout.NORTH);
jf.add(jp,BorderLayout.CENTER);
//设置窗口可视化
jf.setVisible(true);
}
}