用Java设计简易的计算器

运行初始状态:

计算结果如下:

 

代码如下:

package jisuanqi;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;

class counter1 extends JFrame 
{
public counter1()
	 {
	super("计算器");
    this.setSize(400,100);
    this.setLocation(300,240);
    this.setLayout(new FlowLayout());
    TextField text1=new TextField(4);
    text1.setText("1");
    this.add(text1);
    
    String proList[] = { "+","-","x" ,"%"};
    TextField text;
    JComboBox comboBox;
    Container conPane = getContentPane();
    comboBox = new JComboBox(proList);
    comboBox.setEditable(true);
    conPane.add(comboBox);
    
    TextField text2=new TextField(4);
    text2.setText("1");
    this.add(text2);
    JButton button = new JButton("=");
    this.add(button);
    TextField text3=new TextField(4);
    

    button.addActionListener(new ActionListener(){
    	public void actionPerformed(ActionEvent e)
    	{ 
    		String s=comboBox.getEditor().getItem().toString();
    		double a= Integer.parseInt(text1.getText());
    		double b= Integer.parseInt(text2.getText());
    		if(s.equals("+")) {
    			double t=a+b;
    			Integer i2=new Integer((int) t);
    			
    			text3.setText(i2.toString());
    		}
    		else if(s.equals("-"))
    		{double t=a-b;
			Integer i2=new Integer((int) t);
			
			text3.setText(i2.toString());}
    		else if(s.equals("x"))
    		{double t=a*b;
			Integer i2=new Integer((int) t);
			
			text3.setText(i2.toString());}
    		else
    		{double t=a/b;
			Integer i2=new Integer((int) t);
			
			text3.setText(i2.toString());}
    	
    	}});
    conPane.add(text3);
    this.setVisible(true);
	 }



}

public class Counter {
	public static void main(String[] args)
	{
			new counter1();
			}
}

  

 

总结心得:

(1)在创建选项框时,要将所有的选项放在一个“容器”里,并把这个容器添加到程序中,这里我用的容器为JComboBox comboBox,同时需要导入包javax.swing.ComboBoxEditor和javax.swing.JComboBox;

(2)由于设置了按钮响应功能,所以要设置按键动作和响应,这里导入了包java.awt.event.ActionEvent和java.awt.event.ActionListener

(3)因为文本框中输入读取到的是字符串,所以要进行计算时,要先将其转为整形,在文本框输出时,同理要将整形转换为字符串

猜你喜欢

转载自www.cnblogs.com/fjcy/p/10939931.html