⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 calculator.java

📁 计算器程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Calculator
{
	public static void main(String[] args)
	{
		new Standard();
	}
}

//标准型计算器面板,添加动作接口和键盘接口
//先将组件添加到JPanel中,再使用GridbagLayout布局添加到JFrame中
//为所有可获得焦点的组件添加键盘监听
//为可用功能键添加动作监听
class Standard extends JFrame
implements ActionListener,KeyListener
{
	JTextField textout=new JTextField("0");		//输出框
	JButton[] butnum;
	JButton[] butcc;
	JButton[] butmm;
	private AboutDialog aboutdialog;
	GridBagLayout gb;
	GridBagConstraints gbc;
	Container contentPane=getContentPane();
	private double result;		//记录计算结果
	private String lastCommand;	//记录上次输入的计算符
	private String input;		//记录输入的字符
	boolean comstatus=false;	//记录是否存在计算符记录,false则为新计算的开始
	boolean clsstatus=true;		//是否覆盖JTextField的显示,输入字符时
								//true则覆盖,false则追加
	JRadioButtonMenuItem standard;	//标准型的单选按钮
	JRadioButtonMenuItem science;	//科学型的单选按钮

	//标准型布局
	public Standard()
	{
		setTitle("标准型计算器");		//标题
		//contentPane.setBackground(Color.cyan);
		contentPane.setBackground(Color.getHSBColor(0,22,34));
		gb=new GridBagLayout();
		gbc=new GridBagConstraints();
		contentPane.setLayout(gb);		//设置窗口为网格蛋布局
		Font aa=new Font("宋体",Font.BOLD,18);	//运算符较小,放大些,设个大字体
	
		String[] CC={"Backspace","CE","C"};
		String[] NUM={"7","8","9","/","sqrt","4","5","6","*","%"
					,"1","2","3","-","1/x","0","+/-",".","+","="};
		String[] MM={"MC","MR","MS","M+"};
		
		butnum=new JButton[NUM.length];
		butcc=new JButton[CC.length];
		butmm=new JButton[MM.length];
		
		//文本框设为右对齐,不可编辑,背景色为白色
		//添加键盘监听
		//然后将该面板添加到网格蛋布局中
		textout.setHorizontalAlignment(JTextField.RIGHT);
		textout.setEditable(false);
		textout.setBackground(Color.WHITE);
		textout.addKeyListener(this);
		gbc.fill=GridBagConstraints.BOTH;
		addComponent(textout,0,0,6,1);
		
		
		//Backspace,CE,C按纽添加到一个面板中,并且添加动作监听,键盘监听
		//然后将该面板添加到网格蛋布局中
		JPanel ccpanel=new JPanel();
		ccpanel.setBackground(Color.getHSBColor(0,22,34));
		for(int i=0;i<CC.length;i++)
		{
			butcc[i]=new JButton(CC[i]);
			butcc[i].setForeground(Color.red);		//设为红色的字了!!
			ccpanel.add(butcc[i]);
			butcc[i].addActionListener(this);
			butcc[i].addKeyListener(this);
		}
		gbc.fill=GridBagConstraints.NONE;
		addComponent(ccpanel,1,1,6,1);


		//M功能键添加到一个面板中(面板为网格布局),并且添加键盘监听
		//然后将该面板添加到网格蛋布局中		
		JPanel leftpanel=new JPanel();
		leftpanel.setBackground(Color.getHSBColor(0,22,34));
		leftpanel.setLayout(new GridLayout(4,1,5,5));
		

		for(int i=0;i<MM.length;i++)
		{
			butmm[i]=new JButton(MM[i]);
			butmm[i].setForeground(Color.red);
			//butmm[i].setFont(aa);
			leftpanel.add(butmm[i]);
			butmm[i].addKeyListener(this);			
		//	MM[i].addActionListener(this);
		}
		gbc.fill=GridBagConstraints.BOTH;
		addComponent(leftpanel,0,2,1,4);
		
		//数字及计算功能键添加到一个面板中(面板为网格布局),
		//并且添加动作监听和键盘监听
		//然后将该面板添加到网格蛋布局中		
		JPanel numpanel=new JPanel();
		numpanel.setBackground(Color.getHSBColor(0,22,34));
		numpanel.setLayout(new GridLayout(4,5,5,5));
		Icon[] icon=new ImageIcon[10];
		for(int i=0;i<NUM.length;i++)
		{
			//添加了数字图片
			try{
				int k=Integer.parseInt(NUM[i]);		//如果能转化为整形,则为数字
				if(k>=0 && k<10)					
				{
					icon[k]=new ImageIcon("pic\\"+String.valueOf(k)+".gif");
					butnum[i]=new JButton(icon[k]);
					butnum[i].setBackground(new Color(114,162,237));
					numpanel.add(butnum[i]);
					butnum[i].setActionCommand(NUM[i]);
					butnum[i].addActionListener(this);
					butnum[i].addKeyListener(this);
				}
			   }
			catch(Exception e)
			{					
				butnum[i]=new JButton(NUM[i]);
				butnum[i].setBackground(new Color(114,162,237));
				butnum[i].setForeground(Color.blue);
				butnum[i].setFont(aa);
				if((i+1)%5==4 || i==butnum.length-1) butnum[i].setForeground(Color.red);			
				numpanel.add(butnum[i]);
				butnum[i].addActionListener(this);
				butnum[i].addKeyListener(this);
			}
		}
		gbc.fill=GridBagConstraints.BOTH;
		addComponent(numpanel,1,2,5,4);

		menu();		//调用菜单
		
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); //点击关闭按钮时使窗口不关闭
		addWindowListener(new WindowAdapter(){		//关闭窗口时调用自定义的退出对话框
			public void windowClosing(WindowEvent e)
			{
   					int i = JOptionPane.showConfirmDialog(Standard.this,"退出吗?","Message",JOptionPane.YES_NO_OPTION);
         			if (i == JOptionPane.YES_OPTION)
					System.exit(0);
			}
		});

		setLocation(200,200);	//设置窗口位置
		pack();					//压缩
		//显示
		setResizable(false);	//设置不可拖动大小
		show();				
	}
	
	//菜单
	public void menu()
	{
		JMenuBar mb = new JMenuBar();
		setJMenuBar(mb);
		JMenu fileMenu = new JMenu("文件(F)");
		fileMenu.setMnemonic('F');
		JMenu viewMenu = new JMenu("查看(V)");
		viewMenu.setMnemonic('V');
		JMenu helpMenu=new JMenu("帮助(H)");
		helpMenu.setMnemonic('H');

		Icon icon2=new ImageIcon("pic\\collapsed.gif");
		JMenuItem exit=new JMenuItem("退出(X)",icon2);
		exit.setMnemonic('X');
		exit.addActionListener(new			//退出菜单调用自定义的退出对话框
			ActionListener()
			{
				public void actionPerformed(ActionEvent evt)
				{
   					int i = JOptionPane.showConfirmDialog(Standard.this,"退出吗?","Message",JOptionPane.YES_NO_OPTION);
         			if (i == JOptionPane.YES_OPTION)
					System.exit(0);
				}
			});
		fileMenu.addSeparator();
		fileMenu.add(exit);
		mb.add(fileMenu); 
		
		//给类型选择的单选按钮添加动作监听
		//若当前为标准型则只需给科学型的单选按钮添加监听
		ActionListener itemhandler=new ItemHandler();
		standard=new JRadioButtonMenuItem("标准型(T)",true);
		standard.setMnemonic('T');
		science=new JRadioButtonMenuItem("科学型(S)");
		science.setMnemonic('S');
		science.addActionListener( itemhandler );
		
		ButtonGroup bg=new ButtonGroup();	//单选按钮添加到按钮组中
		bg.add(standard);
		bg.add(science);
		viewMenu.add(standard);
		viewMenu.add(science);
		mb.add(viewMenu); 
		
		//关于和退出都使用自定义的对话框
		Icon icon1=new ImageIcon("pic\\addt.gif");
		JMenuItem guanyu=new JMenuItem("关于(G)",icon1);
		guanyu.setMnemonic('G');
		guanyu.addActionListener(new
			ActionListener()
			{
				public void actionPerformed(ActionEvent evt)
				{
					if(aboutdialog==null)
						aboutdialog=new AboutDialog(Standard.this);
					aboutdialog.show();
				}
			});
		helpMenu.add(guanyu);
		mb.add(helpMenu);

	}
	public void addComponent			//GridbagLayout布局设置函数
(Component c,int x,int y,int width,int height)
	{
		gbc.gridx=x;
		gbc.gridy=y;

		gbc.gridwidth=width;
		gbc.gridheight=height;

		gb.setConstraints(c,gbc);
		contentPane.add(c);
	}
	
	public void actionPerformed(ActionEvent event) //点击按钮的动作事件
	{
		input= event.getActionCommand();	//获取输入
		
		if(input.equals("C"))		//输入的是C功能键,则清空记录
		{
			textout.setText("0");	//输出为0
			comstatus=false;		//上次计算符标志位设为false
			clsstatus=true;			//下次输入设为覆盖输出
			return;
		}
		
		if(input.equals("Backspace"))	//如果是退格键
		{
			if(textout.getText().length()>1)	//判断现在输出框里的字符是否大于1个
			{
				textout.setText(textout.getText().substring(
				0,textout.getText().length()-1));	//大于一个就去掉最后一个
			}
			if(textout.getText().length()==1)	//如果是1个就变为0
			{
				textout.setText("0");
			}
		}
		
		try{							
			Integer.parseInt(input);			//将输入转化为Integer型,如果出现异常
			if(clsstatus)						//则输入非数字,如果转化成功则。。。
			{									//如果覆盖标志位为true
				textout.setText(input);			//覆盖输出框输入
				clsstatus=false;				//将覆盖标志位设为false,即下次输入数字
			}									//时可追加输出
			else
			{									//如果覆盖标志位不为true
				textout.setText(textout.getText()+input);	//追加输出
			}
		
		}
		catch(Exception e)
		{
			//小数点比较特殊,输入后覆盖标志位不能取true,继续追加
			if(input.equals("."))
			{
				int la=textout.getText().indexOf("."); //判断目前有没有小数点
				if(la==-1)
				{				
					if(clsstatus)
					{
						textout.setText(input);
						clsstatus=false;
					}
					else
					{
						textout.setText(textout.getText()+input);
					}
				}
			}
			//四则运算调用计算函数
			if(input.equals("+") ||input.equals("-")
				||input.equals("*")||input.equals("/"))
			{
				mathgo();
				clsstatus=true;
			}

			//开方运算符,调用Math类的sqrt(Double)
			if(input.equals("sqrt"))
			{
				textout.setText(String.valueOf(
				Math.sqrt(Double.parseDouble(textout.getText()))));
				clsstatus=true;
			}
			
			//百分号运算符
			if(input.equals("%"))
			{
				textout.setText(String.valueOf(
				result*Double.parseDouble(textout.getText())/100));
				clsstatus=true;
			}
			
			//取倒数运算符			
			if(input.equals("1/x"))
			{
				textout.setText(String.valueOf(
				1/Double.parseDouble(textout.getText())));
				clsstatus=true;
			}
			
			//取反运算符,如>0则在textout.getText()前添加"-"
			//否则,取绝对值
			if(input.equals("+/-"))
			{
				if(Double.parseDouble(textout.getText())>0)
				{
					textout.setText("-"+textout.getText());
				}
				else
				{
					textout.setText(
					String.valueOf(Math.abs(Double.parseDouble(textout.getText()))));
				}
				clsstatus=true;
			}
			//"="运算符,判断是否存在上次运算符,有,则计算出结果
			//否则清楚记录,输出框不变			
			if(input.equals("="))
			{
				if(!comstatus)
				{
					clsstatus=true;
					return;
				}
				else
				{
					lastcom();
					comstatus=false;
					clsstatus=true;
				}
			}
		}
	}

	//计算上次运算符的结果并输出
	public void lastcom()
	{
		if(lastCommand.equals("+"))
		{
			result=result+Double.parseDouble(textout.getText());
			textout.setText(String.valueOf(result));
		}
		if(lastCommand.equals("-"))
		{
			result=result-Double.parseDouble(textout.getText());
			textout.setText(String.valueOf(result));						
		}
		if(lastCommand.equals("*"))
		{
			result=result*Double.parseDouble(textout.getText());
			textout.setText(String.valueOf(result));				
		}
		if(lastCommand.equals("/"))
		{
			result=result/Double.parseDouble(textout.getText());
			textout.setText(String.valueOf(result));						
		}
	}
	
	//四则运算方法
	public void mathgo()
	{
		if(!comstatus)			//如果第一次输入运算符,即上次运算符标志为false
		{
			result=Double.parseDouble(textout.getText());
			comstatus=true;		//上次运算符设为存在
		}
		else
		{
			lastcom();			//计算上次运算的结果并输出
		}
		//输入过计算符,下次输入时将将输出文本框覆盖而不追加,设标志位true

		lastCommand=input;		//更新上次运算符为当前运算符
	}
	
	//键盘事件,keyTyped中可用getKeyChar返回输入的字符
	public void keyTyped(KeyEvent e)
	{
		char keyChar=e.getKeyChar();		//取得键盘输入字符
		String input=String.valueOf(keyChar);	//转化成String型,
		
		if(input.equals("c"))
		{
			textout.setText("0");
			comstatus=false;
			clsstatus=true;
			return;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -