谁能给一个Java的计算器程序代码(加注释 )以前写的 , 给你了
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator {
//计算器面板
private JFrame f = new JFrame("Calculator");
//输入面扳
private JPanel inputPanel = new JPanel();
//加减乘除面板
private JPanel operationPanel = new JPanel();
//数字面板
private JPanel buttonsPanel = new JPanel();
//输入数据文本框
private JTextField input = new JTextField(20);
//退格键
private JButton backspace = new JButton("BackSpace");
//清空
private JButton CE = new JButton("CE");
//删除
private JButton C = new JButton("C");
//四则运算符号键
private JButton add = new JButton(" ");
private JButton sub = new JButton("-");
private JButton mul = new JButton("*");
private JButton div = new JButton("/");
//小数点
private JButton decimal = new JButton(".");
//等号
private JButton equal = new JButton("=");
//数字键
private JButton zero = new JButton("0");
private JButton one = new JButton("1");
private JButton two = new JButton("2");
private JButton three = new JButton("3");
private JButton four = new JButton("4");
private JButton five = new JButton("5");
private JButton six = new JButton("6");
private JButton seven = new JButton("7");
private JButton eight = new JButton("8");
private JButton nine = new JButton("9");
private String num1 = "";//保存第一个运算数字
private String operator = "";//保存运算符号
public static void main(String[] args) {
new Calculator();//new计算器实例
}
public Calculator(){
//添加组件,布局
inputPanel.add(input);
f.add(inputPanel, BorderLayout.NORTH);
operationPanel.add(backspace);
operationPanel.add(CE);
operationPanel.add(C);
f.add(operationPanel, BorderLayout.CENTER);
buttonsPanel.add(add);
buttonsPanel.add(sub);
buttonsPanel.add(mul);
buttonsPanel.add(div);
buttonsPanel.add(one);
buttonsPanel.add(two);
buttonsPanel.add(three);
buttonsPanel.add(zero);
buttonsPanel.add(four);
buttonsPanel.add(five);
buttonsPanel.add(six);
buttonsPanel.add(decimal);
buttonsPanel.add(seven);
buttonsPanel.add(eight);
buttonsPanel.add(nine);
buttonsPanel.add(equal);
buttonsPanel.setLayout(new GridLayout(4, 4));
f.add(buttonsPanel, BorderLayout.SOUTH);
//注册各个组件监听事件
【java复合计算器代码 java计算器正负号如何实现】backspace.addMouseListener(new OperationMouseListener());
CE.addMouseListener(new OperationMouseListener());
C.addMouseListener(new OperationMouseListener());
decimal.addMouseListener(new OperationMouseListener());
equal.addMouseListener(new OperationMouseListener());
//注册四则运算监听
add.addMouseListener(new CalcMouseListener());
sub.addMouseListener(new CalcMouseListener());
mul.addMouseListener(new CalcMouseListener());
div.addMouseListener(new CalcMouseListener());
//注册数字监听事件
zero.addMouseListener(new NumberMouseListener());
one.addMouseListener(new NumberMouseListener());
two.addMouseListener(new NumberMouseListener());
three.addMouseListener(new NumberMouseListener());
four.addMouseListener(new NumberMouseListener());
five.addMouseListener(new NumberMouseListener());
six.addMouseListener(new NumberMouseListener());
seven.addMouseListener(new NumberMouseListener());
eight.addMouseListener(new NumberMouseListener());
nine.addMouseListener(new NumberMouseListener());
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class NumberMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(input.getText().trim().equals("0")){//如果文本框已经是0,结果还是0
input.setText(((JButton)e.getSource()).getText().trim());
}else{//否则的话,把0添加到后面 , 譬如文本框是1 , 结果就为10
input.setText(input.getText().concat(((JButton)e.getSource()).getText().trim()));
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class CalcMouseListener implements MouseListener{
//如果输入的是运算符号,保存第一个结果和运算符号
public void mouseClicked(MouseEvent e) {
num1 = input.getText().trim();input.setText("");
operator = ((JButton)e.getSource()).getText().trim();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class OperationMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(e.getSource() == backspace){//退格键 , 删除一个直到没有字符删除
String inputText = input.getText();
if(inputText.length()0){
input.setText(inputText.substring(0, inputText.length() - 1));
}
}else if(e.getSource() == C){
input.setText("0");//C,清空所有运算数字和符号
num1 = "";
}else if(e.getSource() == CE){
input.setText("0");//CE--将文本框置为0
}else if(e.getSource() == decimal){
String text = input.getText().trim();
//如果按了小数点,如果文本框已经有小数点 , 不做任何操作,否则在结果后面加上小数点
if(text.indexOf(".") == -1){
input.setText(text.concat("."));
}
}else if(e.getSource() == equal){
//如果是等号
if(!operator.trim().equals("")){
if(!input.getText().trim().equals("")){
double result = 0D;
if(operator.equals(" ")){//执行加法运算
result = Double.parseDouble(num1)Double.parseDouble(input.getText().trim());
}else if(operator.equals("-")){//减法运算
result = Double.parseDouble(num1) - Double.parseDouble(input.getText().trim());
}else if(operator.equals("*")){//乘法运算
result = Double.parseDouble(num1) * Double.parseDouble(input.getText().trim());
}else if(operator.equals("/")){//除法运算
result = Double.parseDouble(num1) / Double.parseDouble(input.getText().trim());
}
//格式化最终结果 , 保留两位小数点
input.setText(new DecimalFormat("0.00").format(result));
}
}
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
}
java写的计算器代码 , 有注释//计算器
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class M10 extends WindowAdapter implements MouseListener {
private String first;
private String second;
private String operator;
private Button zero = new Button("0");
private Button one = new Button("1");
private Button two = new Button("2");
private Button three = new Button("3");
private Button four = new Button("4");
private Button five = new Button("5");
private Button six = new Button("6");
private Button seven = new Button("7");
private Button eight = new Button("8");
private Button nine = new Button("9");
private Button decimal = new Button(".");
private Button equal = new Button("=");
private Button add = new Button(" ");
private Button sub = new Button("-");
private Button mul = new Button("*");
private Button div = new Button("/");
private TextField input = new TextField();
private Button CE = new Button("CE");
private Button DEL = new Button("Del");
public static void main(String[] args){
new M10();
}
public M10(){
Frame f = new Frame("Calculator");
f.add("North", input);
Panel keys = new Panel();
f.add(keys, "Center");
keys.setLayout(new GridLayout(4, 4));
keys.add(seven);
keys.add(eight);
keys.add(nine);
keys.add(add);
keys.add(four);
keys.add(five);
keys.add(six);
keys.add(sub);
keys.add(one);
keys.add(two);
keys.add(three);
keys.add(mul);
keys.add(zero);
keys.add(decimal);
keys.add(equal);
keys.add(div);
zero.addMouseListener(this);
one.addMouseListener(this);
two.addMouseListener(this);
three.addMouseListener(this);
four.addMouseListener(this);
five.addMouseListener(this);
six.addMouseListener(this);
seven.addMouseListener(this);
eight.addMouseListener(this);
nine.addMouseListener(this);
add.addMouseListener(this);
sub.addMouseListener(this);
div.addMouseListener(this);
mul.addMouseListener(this);
equal.addMouseListener(this);
decimal.addMouseListener(this);
Panel addtionalPanel = new Panel();
addtionalPanel.setLayout(new GridLayout(1, 2));
addtionalPanel.add(CE);
addtionalPanel.add(DEL);
CE.setBackground(Color.green);
DEL.setBackground(Color.cyan);
CE.addMouseListener(this);
DEL.addMouseListener(this);
f.add("South", addtionalPanel);
f.addWindowListener(this);
f.setVisible(true);
f.setLocation(200, 300);
f.setSize(200, 200);
}
public void windowClosing(WindowEvent e){
System.exit(0);
}
public void mouseClicked(MouseEvent e){
Button btn = (Button)e.getSource();
String key = btn.getActionCommand().trim();
if(btn == one || btn == two || btn == three || btn == zero || btn == four || btn == five || btn == six || btn == seven || btn == eight || btn == nine){
if(isBlank(operator)){
if(isBlank(first)){
first = key;
}
else{
first= key;
}
input.setText(first);
}
else{
if(isBlank(second)){
second = key;
}
else{
second= key;
}
input.setText(second);
}
}
else if(btn == decimal){
if(isBlank(operator)){
if(isBlank(first)){
first = "0.";
input.setText(first);
}
else{
if(first.indexOf(".") == -1){
first= ".";
input.setText(first);
}
}
}
else{
if(isBlank(second)){
second = "0.";
input.setText(second);
}
else{
if(second.indexOf(".") == -1){
second= ".";
input.setText(second);
}
}
}
}
else if(btn == equal){
if(!isBlank(second)!isBlank(first)!isBlank(operator)){
double result = 0.0D;
if(operator.equals(" ")){
result = Double.parseDouble(first)Double.parseDouble(second);
}
else if(operator.equals("-")){
result = Double.parseDouble(first) - Double.parseDouble(second);
}
else if(operator.equals("*")){
result = Double.parseDouble(first) * Double.parseDouble(second);
}
else if(operator.equals("/")){
result = Double.parseDouble(first) / Double.parseDouble(second);
}
int value = https://www.04ip.com/post/(int)Math.round(result);
if(value =https://www.04ip.com/post/= result){
input.setText(String.valueOf(value));
}
else{
input.setText(String.valueOf(result));
}
first = String.valueOf(result);
second = null;
operator = null;
}
}
else if(btn == add || btn == sub || btn == div || btn == mul){
if(!isBlank(first)){
if(!isBlank(operator)!isBlank(second)){
if(operator.equals(" ")){
first = String.valueOf(Double.parseDouble(first)Double.parseDouble(second));
}
else if(operator.equals("-")){
first = String.valueOf(Double.parseDouble(first) - Double.parseDouble(second));
}
else if(operator.equals("*")){
first = String.valueOf(Double.parseDouble(first) * Double.parseDouble(second));
}
else if(operator.equals("/")){
first = String.valueOf(Double.parseDouble(first) / Double.parseDouble(second));
}
second = null;
}
operator = key;
}
}
else if(btn == CE){
first = null;
second = null;
operator = null;
input.setText(null);
}
else if(btn == DEL){
if(isBlank(operator)){
if(!isBlank(first)){
first = first.substring(0, first.length() -1);
input.setText(first);
}
}
else{
if(!isBlank(second)){
second = second.substring(0, second.length() -1);
input.setText(second);
}
}
}
}
private boolean isBlank(String str){
return str == null || str.trim().equals("");
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}
java 计算器代码import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
/**
* 我的计算器 。Cheshi 继承于 JFrame,是计算器的界面
c*/
public class Cheshi extends JFrame {
private Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox = new JTextField("0");
private CalculatorCore core = new CalculatorCore();
private ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
String label = b.getText();
String result = core.process(label);
textbox.setText(result);
}
};
public Cheshi(String title) throws HeadlessException {
super(title);// 调用父类构造方法
setupFrame();// 调整窗体属性
setupControls();// 创建控件
}
private void setupControls() {
setupDisplayPanel();// 创建文本面板
setupButtonsPanel();// 创建按钮面板
}
// 创建按钮面板并添加按钮
private void setupButtonsPanel() {
JPanel panel = new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]{
"7", "8", "9", " ", "C",
"4", "5", "6", "-", "CE",
"1", "2", "3", "*", "",// 空字符串表示这个位置没有按钮
"0", ".", "=", "/", ""
});
this.add(panel, BorderLayout.CENTER);
}
/**
* 在指定的面板上创建按钮
*
* @param panel要创建按钮的面板
* @param labels 按钮文字
*/
private void createButtons(JPanel panel, String[] labels) {
for (String label : labels) {
// 如果 label 为空,则表示创建一个空面板 。否则创建一个按钮 。
if (label.equals("")) {
panel.add(new JPanel());
} else {
JButton b = new JButton(label);
b.addActionListener(listener);// 为按钮添加侦听器
panel.add(b);
}
}
}
// 设置显示面板,用一个文本框来作为计算器的显示部分 。
private void setupDisplayPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
// 调整文本框
private void setupTextbox() {
textbox.setHorizontalAlignment(JTextField.RIGHT);// 文本右对齐
textbox.setEditable(false);// 文本框只读
textbox.setBackground(Color.white);// 文本框背景色为白色
}
// 调整窗体
private void setupFrame() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);// 当窗体关闭时程序结束
this.setLocation(100, 50);// 设置窗体显示在桌面上的位置
this.setSize(300, 200);// 设置窗体大小
this.setResizable(false);// 窗体大小固定
}
// 程序入口
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Cheshi frame = new Cheshi("我的计算器");
frame.setVisible(true);// 在桌面上显示窗体
}
}
/**
* 计算器核心逻辑 。这个逻辑只能处理 1~2 个数的运算 。
*/
class CalculatorCore {
private String displayText = "0";// 要显示的文本
boolean reset = true;
private BigDecimal number1, number2;
private String operator;
private HashMapString, Operator operators = new HashMapString, Operator();
private HashMapString, Processor processors = new HashMapString, Processor();
CalculatorCore() {
setupOperators();
setupProcessors();
}
// 为每种命令添加处理方式
private void setupProcessors() {
processors.put("[0-9]", new Processor() {
public void calculate(String command) {
numberClicked(command);
}
});
processors.put("\\.", new Processor() {
public void calculate(String command) {
dotClicked();
}
});
processors.put("=", new Processor() {
public void calculate(String command) {
equalsClicked();
}
});
processors.put("[ \\-*/]", new Processor() {
public void calculate(String command) {
operatorClicked(command);
}
});
processors.put("C", new Processor() {
public void calculate(String command) {
clearClicked();
}
});
processors.put("CE", new Processor() {
public void calculate(String command) {
clearErrorClicked();
}
});
}
// 为每种 operator 添加处理方式
private void setupOperators() {
operators.put(" ", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.add(number2);
}
});
operators.put("-", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.subtract(number2);
}
});
operators.put("*", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.multiply(number2);
}
});
operators.put("/", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.divide(number2, 30, RoundingMode.HALF_UP);
}
});
}
// 根据命令处理 。这里的命令实际上就是按钮文本 。
public String process(String command) {
for (String pattern : processors.keySet()) {
if (command.matches(pattern)) {
processors.get(pattern).calculate(command);
break;
}
}
return displayText;
}
// 当按下 CE 时
private void clearErrorClicked() {
if (operator == null) {
number1 = null;
} else {
number2 = null;
}
displayText = "0";
reset = true;
}
// 当按下 C 时,将计算器置为初始状态 。
private void clearClicked() {
number1 = null;
number2 = null;
operator = null;
displayText = "0";
reset = true;
}
// 当按下 = 时
private void equalsClicked() {
calculateResult();
number1 = null;
number2 = null;
operator = null;
reset = true;
}
// 计算结果
private void calculateResult() {
number2 = new BigDecimal(displayText);
Operator oper = operators.get(operator);
if (oper != null) {
BigDecimal result = oper.process(number1, number2);
displayText = result.toString();
}
}
// 当按下-*/ 时(这里也可以扩展成其他中间操作符)
private void operatorClicked(String command) {
if (operator != null) {
calculateResult();
}
number1 = new BigDecimal(displayText);
operator = command;
reset = true;
}
// 当按下 . 时
private void dotClicked() {
if (displayText.indexOf(".") == -1) {
displayText= ".";
} else if (reset) {
displayText = "0.";
}
reset = false;
}
// 当按下 0-9 时
private void numberClicked(String command) {
if (reset) {
displayText = command;
} else {
displayText= command;
}
reset = false;
}
// 运算符处理接口
interface Operator {
BigDecimal process(BigDecimal number1, BigDecimal number2);
}
// 按钮处理接口
interface Processor {
void calculate(String command);
}
}
Java编辑一个科学型计算器跟复合型计算器Java编辑一个科学型计算器跟复合型计算器:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.GridLayout;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List; public class CalculaterYYWF extends JFrame {
private JPanel contentPane;
private JTextField textField;
private ListString listSign = new ArrayListString();
private ListDouble listNum = new ArrayListDouble(); public static void main(String[] args) {
new CalculaterYYWF();
} public CalculaterYYWF() {
setResizable(false);
setBackground(new Color(240, 255, 240));
setTitle("有猿无粉牌计算器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 265, 375);
contentPane = new JPanel();
contentPane.setBackground(new Color(224, 255, 255));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(10, 10, 237, 44);
contentPane.add(textField);
textField.setColumns(10);
JPanel panel = new JPanel();
panel.setBackground(new Color(224, 255, 255));
panel.setBounds(10, 64, 237, 273);
contentPane.add(panel);
panel.setLayout(new GridLayout(5, 4, 5, 5));
String stmp = "123 456-789*0.%/()";
for (int i = 0; i18; i) {
JButton j = new JButton(String.valueOf(stmp.charAt(i)));
j.setActionCommand(j.getText());
panel.add(j);
j.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().trim()
e.getActionCommand());
}
});
}
JButton bt_clear = new JButton("C");
panel.add(bt_clear);
bt_clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textField.setText("");
}
});
JButton bt_deng = new JButton("=");
panel.add(bt_deng);
bt_deng.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String expression = textField.getText();
bracketResolve(expression);
}
});
setVisible(true);
} // 逐层消括号并计算
public void bracketResolve(String exp) {
String strjs = convertString(exp);
} }
java计算器代码import java.awt.*;
import java.awt.event.*;
public class lvhaiya{
int tmp,sum,sum1,sum2=1,sum3=1;
String a,b,c,d;String s="";
Frame f=new Frame("计算器");
private String[]name={
"0","1","2","3","4","5","6","7","8","9"," ","-","*","/","=","空格"
};
public Button[] button=new Button[name.length];
TextField t=new TextField("",30);
Panel p=new Panel();
Panel p1=new Panel();
Color color=new Color(100,170,90);
public lvhaiya(){
p1.setLayout(new GridLayout(5,5));
for(int i=0;iname.length;i){
button[i]=new Button(name[i]);
p1.add(button[i]);
}
p.setLayout(new FlowLayout(FlowLayout.LEFT));
p.setBackground(color);
p.add(t);
f.add(p,BorderLayout.NORTH);
f.add(p1,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
f.addWindowListener( new WindowClose());
t.setText("0.");
for(int i=0;iname.length;i){
button[i].addActionListener(new ButtonEventl());
}
}
public static void main(String[]args){
new lvhaiya();
}
class WindowClose extends WindowAdapter{
public void windouClosing(WindowEvent e){
System.exit(0);
}
}
class ButtonEventl implements ActionListener{
public void actionPerformed(ActionEvent e)throws ArithmeticException{
String command=e.getActionCommand();
if(command.equals(" ")){
sum=Integer.parseInt(t.getText()) sum;
t.setText(String.valueOf(sum));
a=t.getText();
s="";
}
else if(command.equals("-")){
sum1=Integer.parseInt(t.getText());
b=t.getText();
s="";
}
else if(command.equals("*")){
sum2=Integer.parseInt(t.getText())*sum2;
t.setText(String.valueOf(sum2));
c=t.getText();
s="";
}
else if(command.equals("/")){
sum3=Integer.parseInt(t.getText());
d=t.getText();
s="";
}
else if(command.equals("=")){
if(a!=null){
t.setText(String.valueOf(sum tmp));
}
if(b!=null){
t.setText(String.valueOf(sum1-tmp));
}
if(c!=null){
t.setText(String.valueOf(sum2*tmp));
}
try{
if(d!=null){
t.setText(String.valueOf(sum3/tmp));
}
}
catch(ArithmeticException a){
t.setText("除数不能为零");
}
}
else if(command.equals("空格")){
sum=0;
a=null;
b=null;
c=null;
d=null;
sum1=0;
sum2=1;
sum3=1;
tmp=0;
t.setText("0");
s="";
}
else{
s=s command;
t.setText(s);
tmp=Integer.parseInt(s);
}
}
}
}
//按钮可以自己美化一下希望可以帮到你
JAVA简单咋做 , 计算器代码简单写了下,代码如下请参照:
/**
* 计算器类
*
* @author Administrator
*
*/
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 3868243398506940702L;
// 文本框
private JTextField result;
// 按钮数组
private JButton[] buttons;
// 按钮文本
private final String[] characters = { "7", "8", "9", "/", "4", "5", "6",
"*", "1", "2", "3", "-", "0", ".", "=", " " };
// 是否为第一个输入的数字
private boolean isFirstDigit = true;
// 运算结果
private double resultNum = 0.0;
// 运算符
private String operator = "=";
public Calculator(String title) {
// 设置标题栏
super(title);
// 初始化各组件
init();
// 注册各组件监听器
registerListener();
// 显示窗体
setVisible(true);
}
/**
* 初始化各组件
*/
private void init() {
// 常用属性初始化
setSize(220, 200);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
/* 文本框对象初始化 */
result = new JTextField("0");
// 文本右对齐
result.setHorizontalAlignment(JTextField.RIGHT);
// 设置是否可编辑
result.setEditable(false);
/* 按钮初始化 */
buttons = new JButton[characters.length];
for (int i = 0; ibuttons.length; i) {
buttons[i] = new JButton(characters[i]);
buttons[i].setFocusable(false); // 不允许按钮定位焦点
}
/* 将文本框与按钮添加到窗体中 */
add(result, BorderLayout.NORTH);
JPanel pnl = new JPanel(new GridLayout(4, 4, 5, 5));
for (JButton jButton : buttons) {
pnl.add(jButton);
}
add(pnl);
this.getContentPane().setFocusable(true);
}
/**
* 注册监听器
*/
private void registerListener() {
for (JButton jButton : buttons) {
jButton.addActionListener(this);
}
// 注册键盘事件
this.getContentPane().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
String text = String.valueOf(e.getKeyChar());
if (Character.isDigit(text.charAt(0)) || ".".equals(text)) { // 数字或小数点
handleNumber(text);
} else if (" -*/=".indexOf(text) != -1) { // 运算符
handleOperator(text);
} else if (e.getKeyCode() == 8) { // 退格键
String tmp = result.getText().trim();
if (tmp.length() == 1) {
result.setText("0");
isFirstDigit = true;
} else {
result.setText(tmp.substring(0, tmp.length() - 1));
}
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
String text = btn.getText().trim();
if (Character.isDigit(text.charAt(0)) || ".".equals(text)) { // 处理数字和小数点
handleNumber(text);
} else { // 处理运算符
handleOperator(text);
}
}
/**
* 处理数字和小数点
*
* @param text
*/
private void handleNumber(String text) {
if (isFirstDigit) { // 第一次输入
if (".".equals(text)) {
this.result.setText("0.");
} else {
this.result.setText(text);
}
} else if ("0".equals(text)"0".equals(this.result.getText())) {
isFirstDigit = true;
return;
} else if (".".equals(text)this.result.getText().indexOf(".") == -1) {
this.result.setText(this.result.getText()".");
} else if (!".".equals(text)) {
this.result.setText(this.result.getText()text);
}
isFirstDigit = false;
}
/**
* 处理运算符
*
* @param text
*/
private void handleOperator(String text) {
switch (operator) { // 处理各项运算适用于JDK1.7版本的
case " ":
resultNum= Double.parseDouble(this.result.getText());
break;
case "-":
resultNum -= Double.parseDouble(this.result.getText());
break;
case "*":
resultNum *= Double.parseDouble(this.result.getText());
break;
case "/":
resultNum /= Double.parseDouble(this.result.getText());
break;
case "=":
resultNum = Double.parseDouble(this.result.getText());
break;
}
// 将文本框的值修改为运算结果
this.result.setText(String.valueOf(resultNum));
// 将点击的运算符放入operator保存
operator = text;
// 下一个数字第一次点击
isFirstDigit = true;
}
public static void main(String[] args) {
new Calculator("My Calculator");
}
}
运行结果如下:
java复合计算器代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java计算器正负号如何实现、java复合计算器代码的信息别忘了在本站进行查找喔 。
推荐阅读
- 广州游戏直播运营,广州直播团队公司
- sap中查看客户信息,如何用sap查客户代码
- 爬虫需要大量ip地址,爬虫爬取需要登录的网站信息
- 小雕显卡这个品牌怎么样,小雕属于什么主板
- vb.net打印 vbnet打印预览word
- 电商不肯退款如何办,电商不退款怎么投诉
- 怎么看出电视的网络是千兆,如何查看电视支持千兆吗
- 钉钉教师用哪个直播软件,钉钉教师直播能看到学生吗
- php获取用户传来数据 php获取当前用户登录id