加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
JiSuanqi.java 2.34 KB
一键复制 编辑 原始数据 按行查看 历史
刘俊峰 提交于 2019-11-17 22:11 . 计算器作业
package cn.edu.shengda;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
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.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class JiSuanqi {
public static void main(String[] args) {
new myFrame("TWY计算器");
}
}
class myFrame extends JFrame {
JTextField text = new JTextField();
JButton[] bt = new JButton[20];
String key[] = new String[] { "ans", "del", "EC", "C", "1", "2", "3", "+", "4", "5", "6", "-", "7", "8", "9", "*",
"0", ".", "=", "/" };
JPanel keyPanel = new JPanel();
boolean finish = false;
double ans=0;
public myFrame(String title) {
super(title);
init();
}
public void init() {
text.setHorizontalAlignment(JTextField.RIGHT);
text.setPreferredSize(new Dimension(0, 40));
text.setFont(new Font("宋体", Font.BOLD, 20));
for (int i = 0; i < bt.length; i++) {
bt[i] = new JButton(key[i]);
}
Container pane = this.getContentPane();
this.add(text, BorderLayout.NORTH);
keyPanel.setLayout(new GridLayout(5, 4, 3, 3));
this.add(keyPanel, BorderLayout.CENTER);
for (int i = 0; i < bt.length; i++) {
keyPanel.add(bt[i]);
bt[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (finish == true) {
text.setText("");
finish = false;
}
String command = e.getActionCommand();
String s = text.getText();
if ("0123456789.+-*/".indexOf(command) >= 0)
text.setText(text.getText() + command);
else if (command.equals("del"))
text.setText(s.substring(0, s.length() - 1));
else if (command.equals("C") || command.equals("EC"))
text.setText("");
else if (command.equals("ans") )
text.setText(text.getText() + ans);
else if (command.equals("=")) {
ans=new calc(s).result;
text.setText(text.getText() + "="+ans);
finish = true;
}
}
});
}
this.setVisible(true);
this.setLocation(500, 200);
this.setSize(325, 325);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化