2024年1月9日发(作者:)
Java语言编写计算器程序 (swing界面)
import Layout;
import yout;
import Event;
import Listener;
import pter;
import nt;
import n;
import ;
import ;
import ield;
public class Calculator extends JFrame
{
//声明一个文本栏控件,用于显示计算结果
private JTextField txtResult;
private JPanel p;
//定义一个字符数组,将计算器中的文字都放在该数组中
private String name[] = {"7", "8", "9", "+", "4", "5", "6", "-", "1",
//声明一个按钮数组,该数组的长度以字符串数组的长度为准
private JButton button[] = new JButton[];
//定义一个存放计算结果的变量,初始为0
private double result = 0;
//存放最后一个操作符,初始为=
private String lastCommand = "=";
//标识是否开始
private boolean start = true;
public Calculator()
{
super("计算器");
//实例化文本栏控件
txtResult = new JTextField(20);
//设置文本框不是焦点状态
"2", "3", "*", "0", ".", "=", "/"};
}
usable(false);
//将文本栏控件放置在窗体框架的上方
(txtResult, );
//实例化面板对象,同时设置此面板布局为4行4列
p = new JPanel(new GridLayout(4, 4));
//循环实例化按钮
//实例化按钮监听对象
ButtonAction ba = new ButtonAction();
//实例化键盘监听对象
KeyAction ka = new KeyAction();
for(int i=0; i<; i++)
{
}
(p, );
e(200, 150);
ation(100, 100);
aultCloseOperation(_ON_CLOSE);
button[i] = new JButton(name[i]);
//注册监听
button[i].addActionListener(ba);
button[i].addKeyListener(ka);
(button[i]);
//计算
public void calculate(double x)
{
if(("+"))
{
}
else if(("-"))
{
}
else if(("*"))
{
}
else if(("/"))
{
}
else if(("="))
{
result /= x;
result *= x;
result -= x;
result += x;
}
}
result = x;
//将结果显示在文本栏
t(""+result);
//单击按钮监听
private class ButtonAction implements ActionListener
{
if(("+")||("-")||("/")||input
}
{
}
else
{
}
if(start)
{
}
t(t()+input);
t("");
start = false;
if(start)
{
}
else
{
}
calculate(ouble(t()));
lastCommand = input;
start = true;
if(("-"))
{
}
else
{
}
lastCommand = input;
t(input);
start = false;
public void actionPerformed(ActionEvent e)
{
String input = ionCommand();
.equals("*")||("="))
}
//键盘监听
private class KeyAction extends KeyAdapter
{
}
public static void main(String[] args)
{
}
Calculator f = new Calculator();
ible(true);
public void KeyTyped(KeyEvent e)
{
}
char key = Char();
if(key == '0'||key == '1'||key == '2'||key == '3'||key ==
{
}
else if(key == '+'||key == '-'||key == '*'||key == '/'||key
{
}
if(start)
{
}
else
{
}
calculate(ouble(t()));
lastCommand = f(key);
start = true;
if(key == '-')
{
}
else
lastCommand = f(key);
t(f(key));
start = false;
if(start)
{
}
t(t()+key);
t("");
start = false;
'4'||key == '5'||key == '6'||key == '7'||key == '8'||key == '9')
== '=')
}
发布者:admin,转转请注明出处:http://www.yc00.com/news/1704798501a1372744.html
评论列表(0条)