用java编写计算器
这个计算器要支持:输入功能nnnn输入一个新的任意精度数nnnn~+将两个数加起来*将两个数乘起来=如果两个数相等那么输出1,否则0<后面的数大那么输入1,否则0D复制最...
这个计算器要支持:
输入 功能
nnnn 输入一个新的任意精度数nnnn
~
+ 将两个数加起来
* 将两个数乘起来
= 如果两个数相等那么输出1,否则0
< 后面的数大那么输入1,否则0
D 复制最后一个数
S 把最后2个数调换位置
; 打出来所有的(剩下的)数
我刚学JAVA,这个就用栈的思路就行。
谢谢了。可以把代码给我站内信谢谢
~ 是输出相反数
这个程序网上很多,我希望有个详细点的,而且是根据这个题目写的。最好批注都有。谢谢
我还有一个java编程问题,对这个问题可能有帮助
http://zhidao.baidu.com/question/120889177.html 展开
输入 功能
nnnn 输入一个新的任意精度数nnnn
~
+ 将两个数加起来
* 将两个数乘起来
= 如果两个数相等那么输出1,否则0
< 后面的数大那么输入1,否则0
D 复制最后一个数
S 把最后2个数调换位置
; 打出来所有的(剩下的)数
我刚学JAVA,这个就用栈的思路就行。
谢谢了。可以把代码给我站内信谢谢
~ 是输出相反数
这个程序网上很多,我希望有个详细点的,而且是根据这个题目写的。最好批注都有。谢谢
我还有一个java编程问题,对这个问题可能有帮助
http://zhidao.baidu.com/question/120889177.html 展开
10个回答
展开全部
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
class Oper // 对一个含+ - * /字符串求值
{
public String operator(String s) {
boolean flag = true;
boolean flag2 = false;
int i, n = 0;
String chr = new String(), theta = "";
double number1 = 0, number2 = 0;
Stack oprstack = new Stack();
oprstack.push("=");
Stack opnstack = new Stack();
for (i = 0; i < s.length(); i++) {
chr = String.valueOf(s.charAt(i));
if (!chr.equals("+") && !chr.equals("-") && !chr.equals("*")
&& !chr.equals("/") && !chr.equals("(") && !chr.equals(")")
&& !chr.equals("s") && !chr.equals("=")) {
flag2 = true;
continue;
} else {
if (flag2 == true && chr.equals("s"))
return "您输入有误!";// 提示“数字+sqrt”式输入错误
flag2 = false;
if (n <= i - 1) // 解决+(问题
{
opnstack.push(s.substring(n, i));
}
n = i + 1;
flag = true;
while (flag) {
switch (precede(String.valueOf(oprstack.peek()), chr))// (String)oprstack.peek()
{
case 3:
oprstack.push(chr); // opr1<opr2
flag = false;
break;
case 2:
oprstack.pop(); // opr1==opr2()
flag = false;
break;
case 1:
theta = String.valueOf(oprstack.pop()); // opr1>opr2
if (theta.equals("s")) // 解决sqrt()问题
{
number1 = Double.parseDouble((String) (opnstack
.pop()));
opnstack.push(String.valueOf(Math.sqrt(number1)));
} else // 解决一般混合运算
{
number2 = Double.parseDouble((String) (opnstack
.pop()));
number1 = Double.parseDouble((String) (opnstack
.pop()));
opnstack.push(String.valueOf(opr(number1, number2,
theta)));
}
flag = true;
break;
case 0:
return "您输入有误!";
}// end switch
}// endwhile
}// endelse
}// endfor
return (String.valueOf(opnstack.pop()));
}// end operator()
public double opr(double x, double y, String theta) // 返回x与y运算值
{
if (theta.equals("+"))
return x + y;
if (theta.equals("-"))
return x - y;
if (theta.equals("*"))
return x * y;
if (theta.equals("/"))
return x / y;
return 0.;
}
public int precede(String chr, String c) // 判断运算符优先级
{
// 1 代表">" 2代表"=" 3代表"<"
if (chr.equals("+") || chr.equals("-")) {
if (c.equals("*") || c.equals("/") || c.equals("(")
|| c.equals("s"))
return 3;
else
return 1;
}
if (chr.equals("*") || chr.equals("/") || chr.equals("s")) {
if (c.equals("("))
return 3;
else
return 1;
}
if (chr.equals("(")) {
if (c.equals(")"))
return 2;
else
return 3;
}
if (chr.equals(")")) {
return 1;
}
if (chr.equals("=")) {
if (c.equals("="))
return 2;
else if (c.equals(")"))
return 0;// 提示括号不匹配式输入错误
else
return 3;
}
return 0;
}// end precede
}// end class oper
public class Calculator extends Frame implements ActionListener {
private String s_show;
private String s_go;
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3=new Panel();
Oper do1 = new Oper();
TextField textfields = new TextField(27);
Dialog dlog=new Dialog(this,"about us");
Label aboutlab=new Label();
String s1;
String sedit;
Button buttons1 = new Button("Backspace");
int screenWidth,screenHeight;
Clipboard clp=Toolkit.getDefaultToolkit().getSystemClipboard();
Calculator() {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
MenuBar mbr=new MenuBar();
setMenuBar(mbr);
Menu edit=new Menu(" do ");
MenuItem copy=new MenuItem("Copy Ctrl+C");
MenuItem zhantie=new MenuItem(" Ctrl+V");
MenuItem exit=new MenuItem("Close Alt+F4");
edit.add(copy);
edit.add(zhantie);
mbr.add(edit);
Menu help=new Menu(" help ");
MenuItem help1=new MenuItem("help theme");
MenuItem about=new MenuItem("about us");
dlog.setAlwaysOnTop(true);
dlog.setResizable(false);
//dlog.setEnabled(false);
s1="学习时兴趣小组做的";
aboutlab.setSize(200, 150);
aboutlab.setText(s1);
dlog.add(aboutlab);
about.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dlog.setVisible(true);
}
});
dlog.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dlog.setVisible(false);
}
});
help.add(help1);
help.add(about);
mbr.add(help);
p1.setBackground(Color.lightGray);
p1.setForeground(Color.red);
p2.setBackground(Color.lightGray);
p2.setForeground(Color.blue);
p1.setLayout(new FlowLayout(FlowLayout.RIGHT, 1,1));
p1.add(textfields);
p1.add(buttons1);
buttons1.addActionListener(this);
p2.setLayout(new GridLayout(5, 4, 10, 16));
this.add(p1, BorderLayout.CENTER);
this.add(p2, BorderLayout.SOUTH);
this.setTitle("Play the window");
this.setResizable(false);
this.setAlwaysOnTop(true);
/**textfields.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
char c=e.getKeyChar();
String textfieldsstr=textfields.toString();
switch(c){
case 1:textfields.setText(textfieldsstr+1);break;
case 2:textfields.setText(textfields.toString()+2);break;
case 3:textfields.setText(textfields.toString()+3);break;
case 4:textfields.setText(textfields.toString()+4);break;
case 5:textfields.setText(textfields.toString()+5);break;
case 6:textfields.setText(textfields.toString()+6);break;
case 7:textfields.setText(textfields.toString()+7);break;
case 8:textfields.setText(textfields.toString()+8);break;
case 9:textfields.setText(textfields.toString()+9);break;
case 0:textfields.setText(textfields.toString()+0);break;
case '*':textfields.setText(textfields.toString()+"*");break;
}
/**if(e.getKeyChar()==1){
textfields.setText(textfields.toString()+1);
}
}
});*///未实现键盘监听
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
screenWidth=screenSize.width;
screenHeight=screenSize.height;
this.setBounds(screenWidth/2-150, screenHeight/2-128, 300, 256);
dlog.setBounds(screenWidth/2-100, screenHeight/2-78, 200, 150);
int i, j = 0, k = 9, r1 = 0, r2 = 0, r3 = 0;
for (i = 0; i < 20; i++) {
j++;
if (j == 4) {
j = 0;
r1++;
Button buttons2_i = new Button();
p2.add(buttons2_i);
buttons2_i.setBackground(Color.cyan);
buttons2_i.addActionListener(this);
switch (r1) {
case 1:
buttons2_i.setLabel("+");
break;
case 2:
buttons2_i.setLabel("-");
break;
case 3:
buttons2_i.setLabel("*");
break;
case 4:
buttons2_i.setLabel("/");
break;
case 5:
buttons2_i.setLabel("=");
break;
}
}// endif
else // else1
{
if (i < 3) {
r2++;
Button buttons2_i = new Button(""); //
p2.add(buttons2_i);
buttons2_i.setBackground(Color.cyan);
buttons2_i.addActionListener(this);
switch (r2) {
case 1:
buttons2_i.setLabel("(");
break;
case 2:
buttons2_i.setLabel(")");
break;
case 3:
buttons2_i.setLabel("sqrt");
break;
}
}// endif
else {
if (i > 16 && i < 19) {
r3++;
Button buttons2_i = new Button("");
p2.add(buttons2_i);
buttons2_i.addActionListener(this);
switch (r3) {
case 1:
buttons2_i.setLabel(".");
break;
case 2:
buttons2_i.setLabel("CE");
break;
}
}// endif
else {
Integer name = new Integer(k);
k--;
s_show = name.toString();
Button buttons2_i = new Button(s_show);
p2.add(buttons2_i);
buttons2_i.addActionListener(this);
}
}
}// end else1
}// end for
s_show = "";
s_go = "";
this.setVisible(true);
}// end Calculator()构造方法
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) // if1
{
if (e.getActionCommand() == "CE")// Del
{
s_show = "";
s_go = "";
textfields.setText(s_show);
} else if (e.getActionCommand() == "Backspace") {
if (s_show.equals("")) {
s_go = "";
textfields.setText("");
} else {
if (s_go.length() > 0)
s_go = s_go.substring(0, s_go.length() - 1);
s_show = s_show.substring(0, s_show.length() - 1);
textfields.setText(s_show);
}
} else if (e.getActionCommand() == ".") {
if (textfields.getText().equals(""))
textfields.setText("0.");
else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
}
} else {
if (e.getActionCommand() != "=") {
if (e.getActionCommand().equals("sqrt")) {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
s_go = s_go.substring(0, s_go.length() - 3);
} else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
}
} else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(do1.operator(s_go)); // ().toString()
}
}// end else
}// end if1
if(e.getSource()=="copy"){
sedit=textfields.getSelectedText();
StringSelection text=new StringSelection(sedit);
clp.setContents(text, null);
}
/**else if(e.getSource()=="zhantie"){
Transferable contents=clp.getContents(this);//返回表示剪贴板当前内容的 transferable 对象。
DataFlavor flavor=DataFlavor.stringFlavor;//
String ss;
if (contents.isDataFlavorSupported(flavor)) {
try
{
int start=textfields.getSelectionStart();
int end=textfields.getSelectionEnd();
//textfields.replaceRange("",start,end);
textfields.setText(ss);
ss = (String)contents.getTransferData(flavor);
int n=textfields.getCaretPosition();
textfields.insert(ss,n);
}catch(Exception ee){
// TODO: handle exception
}
}
}*///未实现剪贴板粘贴功能
// end actionPerformed()
// end class Calculator
}
public static void main(String args[]) {
Calculator cal = new Calculator();
}
}
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
class Oper // 对一个含+ - * /字符串求值
{
public String operator(String s) {
boolean flag = true;
boolean flag2 = false;
int i, n = 0;
String chr = new String(), theta = "";
double number1 = 0, number2 = 0;
Stack oprstack = new Stack();
oprstack.push("=");
Stack opnstack = new Stack();
for (i = 0; i < s.length(); i++) {
chr = String.valueOf(s.charAt(i));
if (!chr.equals("+") && !chr.equals("-") && !chr.equals("*")
&& !chr.equals("/") && !chr.equals("(") && !chr.equals(")")
&& !chr.equals("s") && !chr.equals("=")) {
flag2 = true;
continue;
} else {
if (flag2 == true && chr.equals("s"))
return "您输入有误!";// 提示“数字+sqrt”式输入错误
flag2 = false;
if (n <= i - 1) // 解决+(问题
{
opnstack.push(s.substring(n, i));
}
n = i + 1;
flag = true;
while (flag) {
switch (precede(String.valueOf(oprstack.peek()), chr))// (String)oprstack.peek()
{
case 3:
oprstack.push(chr); // opr1<opr2
flag = false;
break;
case 2:
oprstack.pop(); // opr1==opr2()
flag = false;
break;
case 1:
theta = String.valueOf(oprstack.pop()); // opr1>opr2
if (theta.equals("s")) // 解决sqrt()问题
{
number1 = Double.parseDouble((String) (opnstack
.pop()));
opnstack.push(String.valueOf(Math.sqrt(number1)));
} else // 解决一般混合运算
{
number2 = Double.parseDouble((String) (opnstack
.pop()));
number1 = Double.parseDouble((String) (opnstack
.pop()));
opnstack.push(String.valueOf(opr(number1, number2,
theta)));
}
flag = true;
break;
case 0:
return "您输入有误!";
}// end switch
}// endwhile
}// endelse
}// endfor
return (String.valueOf(opnstack.pop()));
}// end operator()
public double opr(double x, double y, String theta) // 返回x与y运算值
{
if (theta.equals("+"))
return x + y;
if (theta.equals("-"))
return x - y;
if (theta.equals("*"))
return x * y;
if (theta.equals("/"))
return x / y;
return 0.;
}
public int precede(String chr, String c) // 判断运算符优先级
{
// 1 代表">" 2代表"=" 3代表"<"
if (chr.equals("+") || chr.equals("-")) {
if (c.equals("*") || c.equals("/") || c.equals("(")
|| c.equals("s"))
return 3;
else
return 1;
}
if (chr.equals("*") || chr.equals("/") || chr.equals("s")) {
if (c.equals("("))
return 3;
else
return 1;
}
if (chr.equals("(")) {
if (c.equals(")"))
return 2;
else
return 3;
}
if (chr.equals(")")) {
return 1;
}
if (chr.equals("=")) {
if (c.equals("="))
return 2;
else if (c.equals(")"))
return 0;// 提示括号不匹配式输入错误
else
return 3;
}
return 0;
}// end precede
}// end class oper
public class Calculator extends Frame implements ActionListener {
private String s_show;
private String s_go;
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3=new Panel();
Oper do1 = new Oper();
TextField textfields = new TextField(27);
Dialog dlog=new Dialog(this,"about us");
Label aboutlab=new Label();
String s1;
String sedit;
Button buttons1 = new Button("Backspace");
int screenWidth,screenHeight;
Clipboard clp=Toolkit.getDefaultToolkit().getSystemClipboard();
Calculator() {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
MenuBar mbr=new MenuBar();
setMenuBar(mbr);
Menu edit=new Menu(" do ");
MenuItem copy=new MenuItem("Copy Ctrl+C");
MenuItem zhantie=new MenuItem(" Ctrl+V");
MenuItem exit=new MenuItem("Close Alt+F4");
edit.add(copy);
edit.add(zhantie);
mbr.add(edit);
Menu help=new Menu(" help ");
MenuItem help1=new MenuItem("help theme");
MenuItem about=new MenuItem("about us");
dlog.setAlwaysOnTop(true);
dlog.setResizable(false);
//dlog.setEnabled(false);
s1="学习时兴趣小组做的";
aboutlab.setSize(200, 150);
aboutlab.setText(s1);
dlog.add(aboutlab);
about.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dlog.setVisible(true);
}
});
dlog.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dlog.setVisible(false);
}
});
help.add(help1);
help.add(about);
mbr.add(help);
p1.setBackground(Color.lightGray);
p1.setForeground(Color.red);
p2.setBackground(Color.lightGray);
p2.setForeground(Color.blue);
p1.setLayout(new FlowLayout(FlowLayout.RIGHT, 1,1));
p1.add(textfields);
p1.add(buttons1);
buttons1.addActionListener(this);
p2.setLayout(new GridLayout(5, 4, 10, 16));
this.add(p1, BorderLayout.CENTER);
this.add(p2, BorderLayout.SOUTH);
this.setTitle("Play the window");
this.setResizable(false);
this.setAlwaysOnTop(true);
/**textfields.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
char c=e.getKeyChar();
String textfieldsstr=textfields.toString();
switch(c){
case 1:textfields.setText(textfieldsstr+1);break;
case 2:textfields.setText(textfields.toString()+2);break;
case 3:textfields.setText(textfields.toString()+3);break;
case 4:textfields.setText(textfields.toString()+4);break;
case 5:textfields.setText(textfields.toString()+5);break;
case 6:textfields.setText(textfields.toString()+6);break;
case 7:textfields.setText(textfields.toString()+7);break;
case 8:textfields.setText(textfields.toString()+8);break;
case 9:textfields.setText(textfields.toString()+9);break;
case 0:textfields.setText(textfields.toString()+0);break;
case '*':textfields.setText(textfields.toString()+"*");break;
}
/**if(e.getKeyChar()==1){
textfields.setText(textfields.toString()+1);
}
}
});*///未实现键盘监听
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
screenWidth=screenSize.width;
screenHeight=screenSize.height;
this.setBounds(screenWidth/2-150, screenHeight/2-128, 300, 256);
dlog.setBounds(screenWidth/2-100, screenHeight/2-78, 200, 150);
int i, j = 0, k = 9, r1 = 0, r2 = 0, r3 = 0;
for (i = 0; i < 20; i++) {
j++;
if (j == 4) {
j = 0;
r1++;
Button buttons2_i = new Button();
p2.add(buttons2_i);
buttons2_i.setBackground(Color.cyan);
buttons2_i.addActionListener(this);
switch (r1) {
case 1:
buttons2_i.setLabel("+");
break;
case 2:
buttons2_i.setLabel("-");
break;
case 3:
buttons2_i.setLabel("*");
break;
case 4:
buttons2_i.setLabel("/");
break;
case 5:
buttons2_i.setLabel("=");
break;
}
}// endif
else // else1
{
if (i < 3) {
r2++;
Button buttons2_i = new Button(""); //
p2.add(buttons2_i);
buttons2_i.setBackground(Color.cyan);
buttons2_i.addActionListener(this);
switch (r2) {
case 1:
buttons2_i.setLabel("(");
break;
case 2:
buttons2_i.setLabel(")");
break;
case 3:
buttons2_i.setLabel("sqrt");
break;
}
}// endif
else {
if (i > 16 && i < 19) {
r3++;
Button buttons2_i = new Button("");
p2.add(buttons2_i);
buttons2_i.addActionListener(this);
switch (r3) {
case 1:
buttons2_i.setLabel(".");
break;
case 2:
buttons2_i.setLabel("CE");
break;
}
}// endif
else {
Integer name = new Integer(k);
k--;
s_show = name.toString();
Button buttons2_i = new Button(s_show);
p2.add(buttons2_i);
buttons2_i.addActionListener(this);
}
}
}// end else1
}// end for
s_show = "";
s_go = "";
this.setVisible(true);
}// end Calculator()构造方法
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) // if1
{
if (e.getActionCommand() == "CE")// Del
{
s_show = "";
s_go = "";
textfields.setText(s_show);
} else if (e.getActionCommand() == "Backspace") {
if (s_show.equals("")) {
s_go = "";
textfields.setText("");
} else {
if (s_go.length() > 0)
s_go = s_go.substring(0, s_go.length() - 1);
s_show = s_show.substring(0, s_show.length() - 1);
textfields.setText(s_show);
}
} else if (e.getActionCommand() == ".") {
if (textfields.getText().equals(""))
textfields.setText("0.");
else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
}
} else {
if (e.getActionCommand() != "=") {
if (e.getActionCommand().equals("sqrt")) {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
s_go = s_go.substring(0, s_go.length() - 3);
} else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
}
} else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(do1.operator(s_go)); // ().toString()
}
}// end else
}// end if1
if(e.getSource()=="copy"){
sedit=textfields.getSelectedText();
StringSelection text=new StringSelection(sedit);
clp.setContents(text, null);
}
/**else if(e.getSource()=="zhantie"){
Transferable contents=clp.getContents(this);//返回表示剪贴板当前内容的 transferable 对象。
DataFlavor flavor=DataFlavor.stringFlavor;//
String ss;
if (contents.isDataFlavorSupported(flavor)) {
try
{
int start=textfields.getSelectionStart();
int end=textfields.getSelectionEnd();
//textfields.replaceRange("",start,end);
textfields.setText(ss);
ss = (String)contents.getTransferData(flavor);
int n=textfields.getCaretPosition();
textfields.insert(ss,n);
}catch(Exception ee){
// TODO: handle exception
}
}
}*///未实现剪贴板粘贴功能
// end actionPerformed()
// end class Calculator
}
public static void main(String args[]) {
Calculator cal = new Calculator();
}
}
2009-10-22
展开全部
因为有字数限制, 发前半部分
package c;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.MemoryImageSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.plaf.metal.MetalLookAndFeel;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
//该版本是改进版 01
/*///////////////////////////////////////////////////////
*
* @author T
*
* 主要实现了一个计算器框架,内含一个计算方法 calculate
*
* 通过实现包内的Calculator接口可以换成其他的运算方法
*
* 代码上半部分为界面实现,后半部分为表达式运算实现
*
*////////////////////////////////////////////////////////
//=======================================================================
//
//主要框架开始:
public class CalculatorFrame01 extends JFrame implements ActionListener, MouseListener{
//help窗口
class HelpFrame extends JFrame {
private static final long serialVersionUID = 5659419268287608878L;
private Color bkgd=new Color(0,32,68);
public HelpFrame(){
super("Help contents");
setSize(300,300);
setLocation(400,150);
setResizable(false);
setIconImage(icon);
}
public void paint(Graphics g){
g.setColor(bkgd);
g.fillRect(0, 0, 300, 300);
g.setColor(Color.white);
g.drawString("该版本采用的角度制是弧度",10, 60);
g.drawString("圆周率 PI = 3.141592653589793(直接输入PI即可)",10, 100);
g.drawString("自然对数 e = 2.718281828459045(直接输入e即可)",10, 140);
g.drawString("有任何疑问和建议请发至邮箱 talent-001@163.com", 10, 180);
g.drawString("衷心感谢", 130, 220);
g.drawString("By T", 240, 270);
}
}
//about窗口
class AboutFrame extends JFrame {
private static final long serialVersionUID = 5659419268287608877L;
public AboutFrame(){
super("About T's Calculator");
setSize(300,300);
setLocation(400,150);
setResizable(false);
setIconImage(icon);
}
public void paint(Graphics g){
g.setColor(Color.white);
g.drawImage(icon,0,10,300,300,null);
g.drawString("Author T", 200, 60);
g.drawString("E-mail talent-001@163.com",130, 100);
g.drawString("CreateTime 2009.4.23",150, 140);
g.drawString("Advised by ZzxBarry",160, 180);
g.drawString("Acknowledge Java2学习指南 Eclipse Ganymede",20, 240);
g.setColor(Color.gray);
g.drawString("ClassName CalculatorFrame01",110, 280);
}
}
private static final long serialVersionUID = 2087528703614679038L;
//
//
//
//==============================================================================
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//==============================================================================
//上半部分:界面实现
//
//
//==================================================================
//成员--数据域
//文件操作
private FileDialog filedialog = new FileDialog(this,"File");
//主要背景色
private Color backgroundColor = new Color(230,238,238);
//光标位置
private int caretDot;
//结果储存
private String answer="";
//输入,输出区域
public JTextField input = new JTextField(28);
public JTextArea output = new JTextArea(6,33);
//输出区域的滚动窗格
private JScrollPane outPane =new JScrollPane(output);
//窗口容器
private Container mainPane=this.getContentPane();
//右键弹出菜单
private JPopupMenu popupMenu = new JPopupMenu();
//platform look and feel
private LookAndFeel plaf = UIManager.getLookAndFeel();
//图标
public Image icon;
//Help contents
public JFrame help;
//About T's Calculator
public JFrame about;
//计算器数据
//计算器引用,默认初始化为自身
public Calculator calculator = this;
//=====================================================================
//成员--构造器
//默认构造函数
public CalculatorFrame01(){
super("T Calculator");
setSize(400,380);
setLocation(350,100);
setResizable(false);
setLayout(new BorderLayout());
setMenuBar();
setDisplay();
setButton();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setIcon();
mainPane.setLayout(new BorderLayout());
mainPane.setBackground(backgroundColor);
help=new HelpFrame();
about=new AboutFrame();
}
//==================================================================
//成员--方法域
//生成并设置图标
private void setIcon(){
int i,j,k,red,green,blue,h=63,w=63;
int[] pixels=new int[w*h];
for(k=i=0;i<h;i++)
for(j=0;j<w;j++){
red=(i*1^j*1)&0xff;
green=(i*2^j*2)&0xff;
blue=(i*4^j*4)&0xff;
pixels[k++]=0xff000000|(red<<16)|(green<<8)|blue;
}
icon=createImage(new MemoryImageSource(w,h,pixels,0,w));
setIconImage(icon);
}
//定义并设置菜单栏
private void setMenuBar(){
//定义菜单系统
JMenuBar
menuBar=new JMenuBar();
JMenu
fileMenu = new JMenu("File",true),
editMenu = new JMenu("Edit",true),
helpMenu = new JMenu("Help",true);
JMenuItem
openMenuItem = new JMenuItem("Open",'o'),
inMenuItem = new JMenuItem("Save input",'i'),
outMenuItem = new JMenuItem("Save outcome",'s'),
copyMenuItem = new JMenuItem("Copy",'c'),
pasteMenuItem = new JMenuItem("Paste",'p'),
clearMenuItem = new JMenuItem("Clear outcome",'r'),
helpMenuItem = new JMenuItem("Help contents",'h'),
changeMenuItme = new JMenuItem("Change UI",'u'),
aboutMenuItem = new JMenuItem("About T's Calculator",'a'),
popupMenuItem = new JMenuItem("About T's Calculator"),
copyMenuItem1 = new JMenuItem("Copy",'c'),
pasteMenuItem1 = new JMenuItem("Paste",'p');
//设置菜单系统
fileMenu.setMnemonic('F');
editMenu.setMnemonic('E');
helpMenu.setMnemonic('H');
openMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
inMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK));
outMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
copyMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
pasteMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK));
clearMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK));
helpMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
aboutMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
//设置监听器
//这三个是对鼠标右键进行监听
mainPane.addMouseListener(this);
input.addMouseListener(this);
output.addMouseListener(this);
//下面主要是点击监听
openMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
filedialog.setMode(FileDialog.LOAD);
filedialog.setVisible(true);
File fi = new File(filedialog.getDirectory()+filedialog.getFile());
byte[] b = new byte[ (int) fi.length()];
try {
new FileInputStream(fi).read(b);
input.setText(new String(b,0,(int)fi.length()));
} catch (Exception e) {
e.printStackTrace();
}
}
});
inMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
filedialog.setMode(FileDialog.SAVE);
filedialog.setVisible(true);
if(filedialog.getDirectory()!=null&&filedialog.getFile()!=null){
String s=filedialog.getDirectory()+filedialog.getFile();
if(!s.endsWith(".txt"))s+=".txt";
File fi = new File(s);
try {
new FileOutputStream(fi).write(input.getText().getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
outMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
filedialog.setMode(FileDialog.SAVE);
filedialog.setVisible(true);
if(filedialog.getDirectory()!=null&&filedialog.getFile()!=null){
String s=filedialog.getDirectory()+filedialog.getFile();
if(!s.endsWith(".txt"))s+=".txt";
File fi = new File(s);
try {
new FileOutputStream(fi).write(output.getText().getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
copyMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(input. getSelectedText()!=null)input. copy(); else
if(output.getSelectedText()!=null)output.copy();
}
});
pasteMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input.paste();
}
});
clearMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
output.setText("");
}
});
helpMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
help.setVisible(true);
}
});
changeMenuItme.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
changeUI();
}
});
aboutMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
about.setVisible(true);
}
});
copyMenuItem1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(input. getSelectedText()!=null)input. copy(); else
if(output.getSelectedText()!=null)output.copy();
}
});
pasteMenuItem1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input.paste();
}
});
popupMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
about.setVisible(true);
}
});
//组合菜单系统
fileMenu.add(openMenuItem);
fileMenu.add(inMenuItem);
fileMenu.add(outMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
editMenu.addSeparator();
editMenu.add(clearMenuItem);
helpMenu.add(helpMenuItem);
helpMenu.addSeparator();
helpMenu.add(changeMenuItme);
helpMenu.add(aboutMenuItem);
popupMenu.add(copyMenuItem1);
popupMenu.add(pasteMenuItem1);
popupMenu.addSeparator();
popupMenu.add(popupMenuItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
}
//设置显示区域
private void setDisplay(){
//定义
JPanel
TextPanel = new JPanel();
//设置
input.setFont(new Font(input.getFont().getFontName(),Font.PLAIN,15));
input.setText("");
output.setText("");
output.setEditable(false);
TextPanel.setLayout(new FlowLayout());
TextPanel.setBorder(new EmptyBorder(10,0,25,0));
TextPanel.setBackground( backgroundColor);
//设置光标监听器
input.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent ce) {
caretDot=ce.getDot();
}
});
input.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
getOutcome();
}
});
//组合
TextPanel.add(input);
TextPanel.add(outPane);
mainPane.add(TextPanel,BorderLayout.NORTH);
}
//设置按钮
private void setButton(){
//定义
JPanel
rootPanel = new JPanel(),
numPanel = new JPanel(),
funPanel = new JPanel();
Color
numColor = new Color(68,128,168),
funColor = new Color(38,68,138);
Insets
numInsets = new Insets(0,1,0,1),
funInsets = new Insets(0,1,0,1);
String[]
numLabels = {"7","8","9","Del","AC",
"4","5","6","×","÷",
"1","2","3","+","-",
"0",".","^","Ans","=",},
funLabels = {"sin","asin","sinh","(",")",
"cos","acos","cosh","ln","log",
"tan","atan","tanh","sqrt","1/x",
"cot","√","з√","x^2","x^3"};
JButton[]
numButtons=new JButton[numLabels.length],
funButtons=new JButton[funLabels.length];
for(int i=0;i<numLabels.length;i++)numButtons[i]=new JButton(numLabels[i]);
for(int i=0;i<funLabels.length;i++)funButtons[i]=new JButton(funLabels[i]);
//设置
rootPanel.setLayout(new BorderLayout());
rootPanel.setBorder(new EmptyBorder(15,15,15,15));
rootPanel.setBackground(backgroundColor);
numPanel.setBackground( backgroundColor);
funPanel.setBackground( backgroundColor);
numPanel.setLayout(new GridLayout(4,5,2,2));
funPanel.setLayout(new GridLayout(4,5,2,2));
for(JButton button:numButtons){
button.setForeground(numColor);
button.setMargin(numInsets);
button.addActionListener(this);
button.addMouseListener(this);
numPanel.add(button);
}
for(JButton button:funButtons){
button.setForeground(funColor);
button.setMargin(funInsets);
button.addActionListener(this);
button.addMouseListener(this);
funPanel.add(button);
}
//组合
rootPanel.add(numPanel,BorderLayout.EAST);
rootPanel.add(funPanel,BorderLayout.WEST);
mainPane.add(rootPanel,BorderLayout.CENTER);
}
//处理按键动作
public void actionPerformed(ActionEvent ae) {
String command=ae.getActionCommand();
if(command.equals("Del")) {
if(input.getSelectedText()==null&&0<caretDot){
input.setSelectionStart(caretDot-1);
input.setSelectionEnd(caretDot);
}
input.replaceSelection("");
} else
if(command.equals("AC")) {input.setText("");} else
if(command.equals("Ans")) {insert(answer);} else
if(command.equals("1/x")) {input.setText("1/("+input.getText()+")");} else
if(command.equals("x^2")) {insert("^2");} else
if(command.equals("x^3")) {insert("^3");} else
if(command.equals("=")) getOutcome(); else
insert(command);
}
//在input中插入字符串
private void insert(String ins){
if(input.getSelectedText()==null){
input.setSelectionStart(caretDot);
input.setSelectionEnd(caretDot);
}
input.replaceSelection(ins);
}
//计算输入字符串,并把结果添加在output中
private void getOutcome(){
try {
answer=calculator.calculate(input.getText());
} catch (Exception e) {
answer="0.0";
e.printStackTrace();
}
String appended="\r\n"+input.getText()+"\t= "+answer+" ";
output.append(appended);
output.setCaretPosition(output.getText().length());
}
private void changeUI(){
if(plaf instanceof WindowsLookAndFeel){
output.setColumns(33);
plaf = new MetalLookAndFeel();
}else{
output.setColumns(50);
plaf = new WindowsLookAndFeel();
}
try {
UIManager.setLookAndFeel(plaf);
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(this);
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
//主要监听点击右键
public void mouseReleased(MouseEvent me) {
if(me.isPopupTrigger()) popupMenu.show(me.getComponent(),me.getX(),me.getY());
}
public static void main(String[] args) {
new CalculatorFrame01();
}
}
//=====================================================================================
package c;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.MemoryImageSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.plaf.metal.MetalLookAndFeel;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
//该版本是改进版 01
/*///////////////////////////////////////////////////////
*
* @author T
*
* 主要实现了一个计算器框架,内含一个计算方法 calculate
*
* 通过实现包内的Calculator接口可以换成其他的运算方法
*
* 代码上半部分为界面实现,后半部分为表达式运算实现
*
*////////////////////////////////////////////////////////
//=======================================================================
//
//主要框架开始:
public class CalculatorFrame01 extends JFrame implements ActionListener, MouseListener{
//help窗口
class HelpFrame extends JFrame {
private static final long serialVersionUID = 5659419268287608878L;
private Color bkgd=new Color(0,32,68);
public HelpFrame(){
super("Help contents");
setSize(300,300);
setLocation(400,150);
setResizable(false);
setIconImage(icon);
}
public void paint(Graphics g){
g.setColor(bkgd);
g.fillRect(0, 0, 300, 300);
g.setColor(Color.white);
g.drawString("该版本采用的角度制是弧度",10, 60);
g.drawString("圆周率 PI = 3.141592653589793(直接输入PI即可)",10, 100);
g.drawString("自然对数 e = 2.718281828459045(直接输入e即可)",10, 140);
g.drawString("有任何疑问和建议请发至邮箱 talent-001@163.com", 10, 180);
g.drawString("衷心感谢", 130, 220);
g.drawString("By T", 240, 270);
}
}
//about窗口
class AboutFrame extends JFrame {
private static final long serialVersionUID = 5659419268287608877L;
public AboutFrame(){
super("About T's Calculator");
setSize(300,300);
setLocation(400,150);
setResizable(false);
setIconImage(icon);
}
public void paint(Graphics g){
g.setColor(Color.white);
g.drawImage(icon,0,10,300,300,null);
g.drawString("Author T", 200, 60);
g.drawString("E-mail talent-001@163.com",130, 100);
g.drawString("CreateTime 2009.4.23",150, 140);
g.drawString("Advised by ZzxBarry",160, 180);
g.drawString("Acknowledge Java2学习指南 Eclipse Ganymede",20, 240);
g.setColor(Color.gray);
g.drawString("ClassName CalculatorFrame01",110, 280);
}
}
private static final long serialVersionUID = 2087528703614679038L;
//
//
//
//==============================================================================
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//==============================================================================
//上半部分:界面实现
//
//
//==================================================================
//成员--数据域
//文件操作
private FileDialog filedialog = new FileDialog(this,"File");
//主要背景色
private Color backgroundColor = new Color(230,238,238);
//光标位置
private int caretDot;
//结果储存
private String answer="";
//输入,输出区域
public JTextField input = new JTextField(28);
public JTextArea output = new JTextArea(6,33);
//输出区域的滚动窗格
private JScrollPane outPane =new JScrollPane(output);
//窗口容器
private Container mainPane=this.getContentPane();
//右键弹出菜单
private JPopupMenu popupMenu = new JPopupMenu();
//platform look and feel
private LookAndFeel plaf = UIManager.getLookAndFeel();
//图标
public Image icon;
//Help contents
public JFrame help;
//About T's Calculator
public JFrame about;
//计算器数据
//计算器引用,默认初始化为自身
public Calculator calculator = this;
//=====================================================================
//成员--构造器
//默认构造函数
public CalculatorFrame01(){
super("T Calculator");
setSize(400,380);
setLocation(350,100);
setResizable(false);
setLayout(new BorderLayout());
setMenuBar();
setDisplay();
setButton();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setIcon();
mainPane.setLayout(new BorderLayout());
mainPane.setBackground(backgroundColor);
help=new HelpFrame();
about=new AboutFrame();
}
//==================================================================
//成员--方法域
//生成并设置图标
private void setIcon(){
int i,j,k,red,green,blue,h=63,w=63;
int[] pixels=new int[w*h];
for(k=i=0;i<h;i++)
for(j=0;j<w;j++){
red=(i*1^j*1)&0xff;
green=(i*2^j*2)&0xff;
blue=(i*4^j*4)&0xff;
pixels[k++]=0xff000000|(red<<16)|(green<<8)|blue;
}
icon=createImage(new MemoryImageSource(w,h,pixels,0,w));
setIconImage(icon);
}
//定义并设置菜单栏
private void setMenuBar(){
//定义菜单系统
JMenuBar
menuBar=new JMenuBar();
JMenu
fileMenu = new JMenu("File",true),
editMenu = new JMenu("Edit",true),
helpMenu = new JMenu("Help",true);
JMenuItem
openMenuItem = new JMenuItem("Open",'o'),
inMenuItem = new JMenuItem("Save input",'i'),
outMenuItem = new JMenuItem("Save outcome",'s'),
copyMenuItem = new JMenuItem("Copy",'c'),
pasteMenuItem = new JMenuItem("Paste",'p'),
clearMenuItem = new JMenuItem("Clear outcome",'r'),
helpMenuItem = new JMenuItem("Help contents",'h'),
changeMenuItme = new JMenuItem("Change UI",'u'),
aboutMenuItem = new JMenuItem("About T's Calculator",'a'),
popupMenuItem = new JMenuItem("About T's Calculator"),
copyMenuItem1 = new JMenuItem("Copy",'c'),
pasteMenuItem1 = new JMenuItem("Paste",'p');
//设置菜单系统
fileMenu.setMnemonic('F');
editMenu.setMnemonic('E');
helpMenu.setMnemonic('H');
openMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
inMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK));
outMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
copyMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
pasteMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK));
clearMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK));
helpMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
aboutMenuItem. setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
//设置监听器
//这三个是对鼠标右键进行监听
mainPane.addMouseListener(this);
input.addMouseListener(this);
output.addMouseListener(this);
//下面主要是点击监听
openMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
filedialog.setMode(FileDialog.LOAD);
filedialog.setVisible(true);
File fi = new File(filedialog.getDirectory()+filedialog.getFile());
byte[] b = new byte[ (int) fi.length()];
try {
new FileInputStream(fi).read(b);
input.setText(new String(b,0,(int)fi.length()));
} catch (Exception e) {
e.printStackTrace();
}
}
});
inMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
filedialog.setMode(FileDialog.SAVE);
filedialog.setVisible(true);
if(filedialog.getDirectory()!=null&&filedialog.getFile()!=null){
String s=filedialog.getDirectory()+filedialog.getFile();
if(!s.endsWith(".txt"))s+=".txt";
File fi = new File(s);
try {
new FileOutputStream(fi).write(input.getText().getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
outMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
filedialog.setMode(FileDialog.SAVE);
filedialog.setVisible(true);
if(filedialog.getDirectory()!=null&&filedialog.getFile()!=null){
String s=filedialog.getDirectory()+filedialog.getFile();
if(!s.endsWith(".txt"))s+=".txt";
File fi = new File(s);
try {
new FileOutputStream(fi).write(output.getText().getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
copyMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(input. getSelectedText()!=null)input. copy(); else
if(output.getSelectedText()!=null)output.copy();
}
});
pasteMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input.paste();
}
});
clearMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
output.setText("");
}
});
helpMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
help.setVisible(true);
}
});
changeMenuItme.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
changeUI();
}
});
aboutMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
about.setVisible(true);
}
});
copyMenuItem1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(input. getSelectedText()!=null)input. copy(); else
if(output.getSelectedText()!=null)output.copy();
}
});
pasteMenuItem1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
input.paste();
}
});
popupMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
about.setVisible(true);
}
});
//组合菜单系统
fileMenu.add(openMenuItem);
fileMenu.add(inMenuItem);
fileMenu.add(outMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
editMenu.addSeparator();
editMenu.add(clearMenuItem);
helpMenu.add(helpMenuItem);
helpMenu.addSeparator();
helpMenu.add(changeMenuItme);
helpMenu.add(aboutMenuItem);
popupMenu.add(copyMenuItem1);
popupMenu.add(pasteMenuItem1);
popupMenu.addSeparator();
popupMenu.add(popupMenuItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
}
//设置显示区域
private void setDisplay(){
//定义
JPanel
TextPanel = new JPanel();
//设置
input.setFont(new Font(input.getFont().getFontName(),Font.PLAIN,15));
input.setText("");
output.setText("");
output.setEditable(false);
TextPanel.setLayout(new FlowLayout());
TextPanel.setBorder(new EmptyBorder(10,0,25,0));
TextPanel.setBackground( backgroundColor);
//设置光标监听器
input.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent ce) {
caretDot=ce.getDot();
}
});
input.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
getOutcome();
}
});
//组合
TextPanel.add(input);
TextPanel.add(outPane);
mainPane.add(TextPanel,BorderLayout.NORTH);
}
//设置按钮
private void setButton(){
//定义
JPanel
rootPanel = new JPanel(),
numPanel = new JPanel(),
funPanel = new JPanel();
Color
numColor = new Color(68,128,168),
funColor = new Color(38,68,138);
Insets
numInsets = new Insets(0,1,0,1),
funInsets = new Insets(0,1,0,1);
String[]
numLabels = {"7","8","9","Del","AC",
"4","5","6","×","÷",
"1","2","3","+","-",
"0",".","^","Ans","=",},
funLabels = {"sin","asin","sinh","(",")",
"cos","acos","cosh","ln","log",
"tan","atan","tanh","sqrt","1/x",
"cot","√","з√","x^2","x^3"};
JButton[]
numButtons=new JButton[numLabels.length],
funButtons=new JButton[funLabels.length];
for(int i=0;i<numLabels.length;i++)numButtons[i]=new JButton(numLabels[i]);
for(int i=0;i<funLabels.length;i++)funButtons[i]=new JButton(funLabels[i]);
//设置
rootPanel.setLayout(new BorderLayout());
rootPanel.setBorder(new EmptyBorder(15,15,15,15));
rootPanel.setBackground(backgroundColor);
numPanel.setBackground( backgroundColor);
funPanel.setBackground( backgroundColor);
numPanel.setLayout(new GridLayout(4,5,2,2));
funPanel.setLayout(new GridLayout(4,5,2,2));
for(JButton button:numButtons){
button.setForeground(numColor);
button.setMargin(numInsets);
button.addActionListener(this);
button.addMouseListener(this);
numPanel.add(button);
}
for(JButton button:funButtons){
button.setForeground(funColor);
button.setMargin(funInsets);
button.addActionListener(this);
button.addMouseListener(this);
funPanel.add(button);
}
//组合
rootPanel.add(numPanel,BorderLayout.EAST);
rootPanel.add(funPanel,BorderLayout.WEST);
mainPane.add(rootPanel,BorderLayout.CENTER);
}
//处理按键动作
public void actionPerformed(ActionEvent ae) {
String command=ae.getActionCommand();
if(command.equals("Del")) {
if(input.getSelectedText()==null&&0<caretDot){
input.setSelectionStart(caretDot-1);
input.setSelectionEnd(caretDot);
}
input.replaceSelection("");
} else
if(command.equals("AC")) {input.setText("");} else
if(command.equals("Ans")) {insert(answer);} else
if(command.equals("1/x")) {input.setText("1/("+input.getText()+")");} else
if(command.equals("x^2")) {insert("^2");} else
if(command.equals("x^3")) {insert("^3");} else
if(command.equals("=")) getOutcome(); else
insert(command);
}
//在input中插入字符串
private void insert(String ins){
if(input.getSelectedText()==null){
input.setSelectionStart(caretDot);
input.setSelectionEnd(caretDot);
}
input.replaceSelection(ins);
}
//计算输入字符串,并把结果添加在output中
private void getOutcome(){
try {
answer=calculator.calculate(input.getText());
} catch (Exception e) {
answer="0.0";
e.printStackTrace();
}
String appended="\r\n"+input.getText()+"\t= "+answer+" ";
output.append(appended);
output.setCaretPosition(output.getText().length());
}
private void changeUI(){
if(plaf instanceof WindowsLookAndFeel){
output.setColumns(33);
plaf = new MetalLookAndFeel();
}else{
output.setColumns(50);
plaf = new WindowsLookAndFeel();
}
try {
UIManager.setLookAndFeel(plaf);
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(this);
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
//主要监听点击右键
public void mouseReleased(MouseEvent me) {
if(me.isPopupTrigger()) popupMenu.show(me.getComponent(),me.getX(),me.getY());
}
public static void main(String[] args) {
new CalculatorFrame01();
}
}
//=====================================================================================
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
while(true){
String str = sc.next(); //读控制台输入
if("#".equals(str)){
break;
}
// 判断是否操作数
if (str.matches("^(\\-?)(\\d+)(.\\d+)?$"))
stack.push(str);//把操作数或者操作符压入栈
// 如是
else if ("~".equals(str)) {
stack.push("-"+stack.pop());
}
else if("+".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1+op2+"");
}
else if("-".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1-op2+"");
}
else if("*".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1*op2+"");
}
else if("/".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1/op2+"");
}
else if("D".equalsIgnoreCase(str)){
stack.push(stack.peek());
}
}
String temp = stack.pop();
System.out.println(temp);
}
}
String str = sc.next(); //读控制台输入
if("#".equals(str)){
break;
}
// 判断是否操作数
if (str.matches("^(\\-?)(\\d+)(.\\d+)?$"))
stack.push(str);//把操作数或者操作符压入栈
// 如是
else if ("~".equals(str)) {
stack.push("-"+stack.pop());
}
else if("+".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1+op2+"");
}
else if("-".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1-op2+"");
}
else if("*".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1*op2+"");
}
else if("/".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1/op2+"");
}
else if("D".equalsIgnoreCase(str)){
stack.push(stack.peek());
}
}
String temp = stack.pop();
System.out.println(temp);
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
转载
import java.util.Scanner;
import java.util.Stack;
public class StackCal {
public static void main(String[] args){
System.out.println("请输入操作数或者操作符以空格分开 以#号表示输入结束");
Scanner sc = new Scanner(System.in);
Stack<String> stack = new Stack();
while(true){
String str = sc.next(); //读控制台输入
if("#".equals(str)){
break;
}
// 判断是否操作数
if (str.matches("^(\\-?)(\\d+)(.\\d+)?$"))
stack.push(str);//把操作数或者操作符压入栈
// 如是
else if ("~".equals(str)) {
stack.push("-"+stack.pop());
}
else if("+".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1+op2+"");
}
else if("-".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1-op2+"");
}
else if("*".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1*op2+"");
}
else if("/".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1/op2+"");
}
else if("D".equalsIgnoreCase(str)){
stack.push(stack.peek());
}
}
String temp = stack.pop();
System.out.println(temp);
}
}
import java.util.Scanner;
import java.util.Stack;
public class StackCal {
public static void main(String[] args){
System.out.println("请输入操作数或者操作符以空格分开 以#号表示输入结束");
Scanner sc = new Scanner(System.in);
Stack<String> stack = new Stack();
while(true){
String str = sc.next(); //读控制台输入
if("#".equals(str)){
break;
}
// 判断是否操作数
if (str.matches("^(\\-?)(\\d+)(.\\d+)?$"))
stack.push(str);//把操作数或者操作符压入栈
// 如是
else if ("~".equals(str)) {
stack.push("-"+stack.pop());
}
else if("+".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1+op2+"");
}
else if("-".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1-op2+"");
}
else if("*".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1*op2+"");
}
else if("/".equals(str)){
double op2 = Double.parseDouble(stack.pop());
double op1 = Double.parseDouble(stack.pop());
stack.push(op1/op2+"");
}
else if("D".equalsIgnoreCase(str)){
stack.push(stack.peek());
}
}
String temp = stack.pop();
System.out.println(temp);
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2009-10-31
展开全部
TextField textfields = new TextField(27);
Dialog dlog=new Dialog(this,"about us");
Label aboutlab=new Label();
String s1;
String sedit;
Button buttons1 = new Button("Backspace");
int screenWidth,screenHeight;
Clipboard clp=Toolkit.getDefaultToolkit().getSystemClipboard();
Dialog dlog=new Dialog(this,"about us");
Label aboutlab=new Label();
String s1;
String sedit;
Button buttons1 = new Button("Backspace");
int screenWidth,screenHeight;
Clipboard clp=Toolkit.getDefaultToolkit().getSystemClipboard();
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询