发布网友 发布时间:2022-04-23 14:49
共1个回答
热心网友 时间:2023-11-01 07:47
GUI做的计算器,可以查考一下,组件、事件等
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame{
private Container container;//框架
private JTextField tf;//定义文本框
private Panel panel;
private String cmd;
private double result;//运算结果
private boolean start;//运算开始判断
Calculator(){
super("计算器");
container = getContentPane();
container.setLayout(new BorderLayout());
//添加文本框
tf = new JTextField("0.0");
container.add(tf,BorderLayout.NORTH);
tf.setHorizontalAlignment(JTextField.RIGHT);
tf.setEditable(false);
//嵌套容器
panel = new Panel();
container.add(panel);
start = true;
result = 0;
//最后运算等号
cmd = "=";
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
//调用创建Button方法
addButton("1",insert);
addButton("2",insert);
addButton("3",insert);
addButton("0",insert);
addButton("*",command);
addButton("Back",insert);
addButton("4",insert);
addButton("5",insert);
addButton("6",insert);
addButton("+",command);
addButton("/",command);
addButton("Clear",insert);
addButton("7",insert);
addButton("8",insert);
addButton("9",insert);
addButton("-",command);
addButton(".",insert);
addButton("=",command);
setSize(400,200);
}
private void addButton(String str,ActionListener listener){
//添加Button方法(操作类型、注册*)
JButton button=new JButton(str);
button.addActionListener(listener);
panel.setLayout(new GridLayout(3,6));
panel.add(button);
}
private class InsertAction implements ActionListener{
//插入,insert
public void actionPerformed(ActionEvent event){
String input=event.getActionCommand();
if (start)
{
tf.setText("");
start=false;
}
if(input.equals("Back"))
{
String str=tf.getText();
if(str.length()>0)
tf.setText(str.substring(0,str.length()-1));
}
else if(input.equals("Clear"))
{
tf.setText("0");
start=true;
}
else
tf.setText(tf.getText()+input);
}
}
private class CommandAction implements ActionListener{
//计算,command
public void actionPerformed(ActionEvent e){
String command=e.getActionCommand();
if(start)
{
cmd=command;
}
else
{
calculate(Double.parseDouble(tf.getText()));
cmd=command;
start=true;
}
}
}
public void calculate(double x){
//加减乘除运算
if (cmd.equals("+")) result+=x;
else if (cmd.equals("-")) result-=x;
else if (cmd.equals("*")) result*=x;
else if (cmd.equals("/")) result/=x;
else if (cmd.equals("=")) result= x;
tf.setText(""+ result);
}
public static void main(String []args){
Calculator mycalculator=new Calculator();
mycalculator.setLocation(300,300);
mycalculator.setVisible(true);
}
}