JAVA(GUI)——制作简易计算器
界面的设置
整体为5*4的框体,所应用的控件主要为TextField和Btton。TextField用来显示所选数字以及计算结果,Button用来进行选择数字以及功能。
JTextField text;
JButton []button= new JButton[20];
界面如下:
对各控件进行初始化
对TextField和Button进行界面的设置,使用流式布局。
setLayout(new FlowLayout());
text=new JTextField("",22);
text.setHorizontalAlignment(text.RIGHT);;
add(text);
button[0]=new JButton("sqrt");
button[1]=new JButton(" +/- ");
之后的Button控件初始化与后两行类似
设置各类初始变量
为之后的文本框能够正确显示答案做准备。
int cout=0;//记录符号个数
ArrayList<String> list = new ArrayList<String>();//用来存该运算中的数,以及运算结果,由文本编辑框得到
ArrayList<String> lists = new ArrayList<String>();//用来存该运算中使用了的运算符,当点击运算符按钮存起集合lists
添加事件监听
数字响应事件与运算符响应事件以及其他按钮响应事件有所不同,分开用来展示
添加数字事件监听
每当选择一个数字时,在文本框内将会输入当前选择数字
button[12]=new JButton(" 1 ");
button[12].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
text.setText(text.getText()+"1");
}
});
button[13]=new JButton(" 2 ");
button[13].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
text.setText(text.getText()+"2");
}
});
button[14]=new JButton(" 3 ");
button[14].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
text.setText(text.getText()+"3");
}
});
其他各项数字类似
添加运算符事件监听
当选择到运算符的按钮时,记录当前选择的运算符,cout++。并将之前文本框内所选择的数字放入队列中,清空当前文本,以方便下一个数字的输入。
button[19]=new JButton(" + ");
button[19].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
list.add(text.getText()); //运算的实现,获取在文本编辑框上显示的文本,并存入集合list中
lists.add("+"); //获取运算符,存入lists中
cout++; //标记运算符的个数,也就是要进行运算的次数
text.setText(""); //将编辑框置为空的,方便下一个数据的额输入
}
});
其余几个运算符类似
添加其他按钮事件监听
例如清除按钮,退格按钮,改变正负按钮等
button[3]=new JButton("<- ");//退格按钮
button[3].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String message;
int length=text.getText().length();
message=text.getText();
if(length==0)
{
text.setText("");
}
else
{
text.setText(message.