java基础计算器的一些代码
/** To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package 利用鼠标;
import java.awt.FlowLayout;
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.JTextField;
/**
*
* @Author Administrator
*/
public class Adder {
JFrame frame;
JLabel label_num1,label_num2,label_result;
JTextField tf_num1,tf_num2,tf_result;
JButton bt1,bt2,bt3,bt4;
public Adder(){
frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭按钮
frame.setSize(300,200); //设置尺寸
label_num1=new JLabel("num1");
tf_num1=new JTextField(20); //控制输入长度
label_num2=new JLabel("num2");
tf_num2=new JTextField(20);
label_result=new JLabel("result");
tf_result=new JTextField(20);
bt1=new JButton("+");
frame.setLayout(new FlowLayout());
Mylistener mylistener=new Mylistener();
bt1.addActionListener(mylistener); //在按钮上加一个监视器
bt2=new JButton("-");
Mylistener2mylistener2=new Mylistener2();
bt2.addActionListener(mylistener2);
bt3=new JButton("*");
Mylistener3 mylistener3=new Mylistener3();
bt3.addActionListener(mylistener3);
bt4=new JButton("/");
Mylistener4 mylistener4=new Mylistener4();
bt4.addActionListener(mylistener4);
frame.add(label_num1); //编写的时候必须按顺序与界面显示的顺序相对
frame.add(tf_num1);
frame.add(label_num2);
frame.add(tf_num2);
frame.add(label_result);
frame.add(tf_result);
frame.add(bt1);
frame.add(bt2);
frame.add(bt3);
frame.add(bt4);
frame.setVisible(true); //使界面可视
}
class Mylistener implements ActionListener{
public voidactionPerformed(ActionEvent e){
String num1=tf_num1.getText();
String num2=tf_num2.getText();
int n1=Integer.parseInt(num1); //字符串转换为整形
int n2=Integer.parseInt(num2);
int n=n1+n2;
tf_result.setText(n+" "); //整形转换为字符串()加空格
}
}
class Mylistener2 implements ActionListener{
public voidactionPerformed(ActionEvent e){
String num1=tf_num1.getText();
String num2=tf_num2.getText();
int n1=Integer.parseInt(num1); //字符串转换为整形
int n2=Integer.parseInt(num2);
int n=n1-n2;
tf_result.setText(n+" "); //整形转换为字符串()加空格
}
}
class Mylistener3 implements ActionListener{
public voidactionPerformed(ActionEvent e){
String num1=tf_num1.getText();
String num2=tf_num2.getText();
int n1=Integer.parseInt(num1); //字符串转换为整形
int n2=Integer.parseInt(num2);
int n=n1*n2;
tf_result.setText(n+" ");
//整形转换为字符串()加空格
}
}
class Mylistener4 implements ActionListener{
public voidactionPerformed(ActionEvent e){
String num1=tf_num1.getText();
String num2=tf_num2.getText();
int n1=Integer.parseInt(num1); //字符串转换为整形
int n2=Integer.parseInt(num2);
int n=n1/n2;
tf_result.setText(n+" "); //整形转换为字符串()加空格
}
}
public static void main(String args[]){
Adder add=new Adder();
}
}
谢谢,谢谢。 额,我改了double ,doublen2=Double.parseDouble(num2);
结果有偏差啊,是因为强制转换时丢失了吗 谢谢楼主分享
页:
[1]