使用Java语言编写一个简易的可以实现加、减、乘、除运算的程序,主要的方法是对Java面板组件的应用和数据类型的转换。
package one;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
public class 计算器 extends JFrame{
/*
* 1、实现输入数据的界面包括运算符
* 2、将数据从字符串类型转换成浮点型数据
* 3、将得到的结果输出到界面
*/
public void creat() {
GridLayout gl=new GridLayout(5,1,10,10);
this.setLayout(gl);
JLabel jl=new JLabel("计算器");
Font font=new Font("宋体",Font.BOLD,36);
jl.setFont(font);
jl.setHorizontalAlignment(SwingConstants.CENTER);
JLabel jl1=new JLabel("数据1");
JTextField jtf1=new JTextField(10);
JPanel p1=new JPanel();
p1.add(jl1);
p1.add(jtf1);
JLabel jl2=new JLabel("数据2");
JTextField jtf2=new JTextField(10);
JPanel p2=new JPanel();
p2.add(jl2);
p2.add(jtf2);
JLabel jl3=new JLabel("结果");
JTextField jtf3=new JTextField(10);
JPanel p3=new JPanel();
p3.add(jl3);
p3.add(jtf3);
JButton b1=new JButton("+");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s1=jtf1.getText();
String s2=jtf2.getText();
float f1=Float.parseFloat(s1);
float f2=Float.parseFloat(s2);
float sum=f1+f2;
jtf3.setText(Float.toString(sum));
}
});
JButton b2=new JButton("-");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s1=jtf1.getText();
String s2=jtf2.getText();
float f1=Float.parseFloat(s1);
float f2=Float.parseFloat(s2);
float sum=f1-f2;
jtf3.setText(Float.toString(sum));
}
});
JButton b3=new JButton("*");
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s1=jtf1.getText();
String s2=jtf2.getText();
float f1=Float.parseFloat(s1);
float f2=Float.parseFloat(s2);
float sum=f1*f2;
jtf3.setText(Float.toString(sum));
}
});
JButton b4=new JButton("/");
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s1=jtf1.getText();
String s2=jtf2.getText();
float f1=Float.parseFloat(s1);
float f2=Float.parseFloat(s2);
float sum=f1/f2;
jtf3.setText(Float.toString(sum));
}
});
JPanel p4=new JPanel();
p4.add(b1);
p4.add(b2);
p4.add(b3);
p4.add(b4);
this.add(jl);
this.add(p1);
this.add(p2);
this.add(p3);
this.add(p4);
this.setSize(450, 400);
this.setVisible(true);
this.setTitle("计算器");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
计算器 jsq=new 计算器();
jsq.creat();
}
}

最后
以上就是大意微笑最近收集整理的关于Java实现简易计算器的全部内容,更多相关Java实现简易计算器内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复