java awt程序_使用AWT制作简单计算器的Java程序

java awt程序

Hello everyone, in this program I am going to share a code to make a simple calculator in java using awt. This calculator works on two integer numbers. As you enter two numbers and then click on desired button, the result is shown in Result text field. When you will click on Cancel button, the calculator will be closed. So just go through the code and try it. If you have any difficulty in understanding or using the code, then you ask by commenting below.

大家好,在此程序中,我将共享一个代码,以使用awt在java中创建一个简单的计算器。 该计算器适用于两个整数。 输入两个数字 ,然后单击所需的按钮时,结果将显示在“结果”文本字段中。 当您单击取消按钮时,计算器将关闭。 因此,只需遍历代码并尝试。 如果您在理解或使用代码方面有任何困难,请在下面的注释中提问。

Java Program to Make a Simple Calculator Using AWT
import java.awt.*;
import java.awt.event.*;
 
class Calculator implements ActionListener
{
	//Declaring Objects
	Frame f=new Frame();
	Label l1=new Label("First Number");
	Label l2=new Label("Second Number");
	Label l3=new Label("Result");
	
	TextField t1=new TextField();
	TextField t2=new TextField();
	TextField t3=new TextField();
	
	Button b1=new Button("Add");
	Button b2=new Button("Sub");
	Button b3=new Button("Mul");
	Button b4=new Button("Div");
	Button b5=new Button("Cancel");
	
	Calculator()
	{
		//Giving Coordinates
		l1.setBounds(50,100,100,20);
		l2.setBounds(50,140,100,20);
		l3.setBounds(50,180,100,20);
		
		t1.setBounds(200,100,100,20);
		t2.setBounds(200,140,100,20);
		t3.setBounds(200,180,100,20);
		
		b1.setBounds(50,250,50,20);
		b2.setBounds(110,250,50,20);
		b3.setBounds(170,250,50,20);
		b4.setBounds(230,250,50,20);
		b5.setBounds(290,250,50,20);
		
		//Adding components to the frame
		f.add(l1);
		f.add(l2);
		f.add(l3);
		
		f.add(t1);
		f.add(t2);
		f.add(t3);
		
		f.add(b1);
		f.add(b2);
		f.add(b3);
		f.add(b4);
		f.add(b5);
		
		b1.addActionListener(this);
		b2.addActionListener(this);
		b3.addActionListener(this);
		b4.addActionListener(this);
		b5.addActionListener(this);
		
		f.setLayout(null);
		f.setVisible(true);
		f.setSize(400,350);
	}
	
	public void actionPerformed(ActionEvent e)
	{
		int n1=Integer.parseInt(t1.getText());
		int n2=Integer.parseInt(t2.getText());
		
		if(e.getSource()==b1)
		{
			t3.setText(String.valueOf(n1+n2));
		}
			
		if(e.getSource()==b2)
		{
			t3.setText(String.valueOf(n1-n2));
		}
		
		if(e.getSource()==b3)
		{
			t3.setText(String.valueOf(n1*n2));
		}
		
		if(e.getSource()==b4)
		{
			t3.setText(String.valueOf(n1/n2));
		}
		
		if(e.getSource()==b5)
		{
			System.exit(0);
		}
	}
	
	public static void main(String...s)
	{
		new Calculator();
	}
}

翻译自: https://www.thecrazyprogrammer.com/2013/09/java-program-to-make-simple-calculator.html

java awt程序

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值