在这里插入代码片
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.awt.datatransfer.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
/**
*
* @author 你不及她
*/
class myException extends Exception{
public myException() {
super();
}
public myException(String msg){
super(msg);
}
}
public class FlowWindow extends JFrame implements ActionListener {
private Frame f;
private JTextField textField;
private String result;
private String ss=" ";
private String jj=" ";
private JMenuItem copy;
private JMenuItem paste;
private JMenuItem read;
private Clipboard clipboard;
private JButton s[]=new JButton[24];
private JMenu m[]=new JMenu[5];//菜单
private JMenuItem about;
private TextArea ta;
private JMenuItem openItem, saveItem, closeItem;
private FileDialog openDia, saveDia;
private File file;
public FlowWindow(){
result="";
this.setBackground(Color.LIGHT_GRAY);
JPanel panel2=new JPanel();
textField = new JTextField(30);
textField.setEditable(false);
textField.setBackground(Color.GREEN);
textField.setPreferredSize(new Dimension(200,50));
this.add(textField, BorderLayout.NORTH);
panel2.setLayout(new GridLayout(4,6,1,1));
String []a={"←","C","0","+","-","*","1","2","3","/","%","D","4","5","6","√","^","Π","7","8","9",".","!","="};
//JButton s[]=new JButton[24];
for(int i=0;i<s.length;i++){
s[i]=new JButton(a[i]);
panel2.add(s[i]);
s[i].addActionListener(new ButtonHandler1());
}
panel2.setBackground(Color.red);
this.add(panel2,BorderLayout.CENTER);
JMenuBar mb = new JMenuBar();
String colors[]={"green","yellow","blue","red","orange","pink","gray"};
String colors2[]={"green1","yellow1","blue1","red1","white1","pink1","gray1","orange1"};
// 菜单
// JMenu m[]=new JMenu[4];
m[0] = new JMenu("编辑");
JMenuItem copy=new JMenuItem("复制");
JMenuItem paste=new JMenuItem("粘贴");
copy.addActionListener(new CopyListener());
paste.addActionListener(new PasteListener());
m[0].add(copy);
m[0].add(paste);
m[1] = new JMenu("设置");
m[3] = new JMenu("帮助");
m[2]=new JMenu("文件");
openItem = new JMenuItem("打开");//创建"打开"菜单项
saveItem = new JMenuItem("保存");//创建"保存"菜单项
closeItem = new JMenuItem("退出");
m[2].add(openItem);
m[2].add(saveItem);
m[2].add(closeItem);
openDia = new FileDialog(this, "打开", FileDialog.LOAD);
saveDia = new FileDialog(this, "保存", FileDialog.SAVE);
myEvent();
about=new JMenuItem("关于");
m[3].add(about);
about.addActionListener(this);
JMenu color[]=new JMenu[2];
JMenuItem m1[]=new JMenuItem[8];
color[0]=new JMenu("按钮颜色");
color[1]=new JMenu("text颜色");
m[1].add(color[0]);
m[1].add(color[1]);
for(int i=0;i<6;i++){
m1[i]=new JMenuItem(colors[i]);
color[0].add( m1[i]);
m1[i].addActionListener(new ButtonHandler2());
}
for(int i=0;i<8;i++){
m1[i]=new JMenuItem(colors2[i]);
color[1].add( m1[i]);
m1[i].addActionListener(new ButtonHandler2());
}
mb.add(m[0]);
mb.add(m[1]);
mb.add(m[2]);
mb.add(m[3]);
// 把菜单栏加入到frame,这里用的是set而非add
this.setJMenuBar(mb);
clipboard= Toolkit.getDefaultToolkit().getSystemClipboard();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
class ButtonHandler1 implements ActionListener{//运算按钮监听
public void actionPerformed(ActionEvent e){
String s=e.getActionCommand();
int a=0;
int b=0;
int c=0;//判断6++
int d=0;//判断6.6.6
if(s=="+"||s=="-"||s=="*"||s=="/"||s=="%"||s=="^"||s=="."){
// System.out.println(result);
// result=result;
// System.out.println(result);
ss=result.substring(result.length()-1, result.length());//记录当前最后一位
System.out.println(ss);
// if(result.length()>2){
// jj=result.substring(result.length()-2,result.length()-1);//记录倒数第二位
// System.out.println(jj);
// }
if(ss.equals("+")||ss.equals("-")||ss.equals("*")||ss.equals("/")||ss.equals("%")||ss.equals("^")||ss.equals(".")){
c=1;
}
// if(jj.equals(".")){
// d=2;
// }
}
if(s.equals("C")) {
result="";
d=0;
}
else if(s.equals("D")&&result.length()==1){
result="1/"+result;
}
// else if(s.equals(".")&&(d==2)){
// d=0;
// System.out.println("error2");
//
// result=result.substring(0,result.length());
// }
else if ((s=="+"||s=="-"||s=="*"||s=="/"||s=="D"||s=="%"||s=="^"||s=="."||s=="!")&&(c==1)){
System.out.println("error1");
result=result.substring(0,result.length());
}
else if(s=="←"){
b=result.length();
result=result.substring(0,b-1);//删去字符串最后一位
}
else if(s.equals("=")) { //按下等号
try{
result+= "="+calculate(result);
}catch(myException ex) {
if(ex.getMessage().equals("被除数不能为0"))
result = ex.getMessage();
else
result = ex.getMessage();}
textField.setText(result);
a = 1;
c=0;
result="";
}
else{
result +=s; }
if(a==0){
textField.setText(result);
} }
}
class ButtonHandler2 implements ActionListener{//设置按钮监听
public void actionPerformed(ActionEvent e){
String a=e.getActionCommand();
switch(a){
case "green1" : textField.setBackground(Color.green);break;
case "yellow1": textField.setBackground(Color.yellow);break;
case "blue1" :textField.setBackground(Color.blue);break;
case "red1" : textField.setBackground(Color.red);break;
case "white1": textField.setBackground(Color.white);break;
case "gray1" :textField.setBackground(Color.gray);break;
case "pink1" : textField.setBackground(Color.pink);break;
case "orange1": textField.setBackground(Color.orange);break;
}
if(a.equals("green")){
for(int i=0;i<24;i++) {
s[i].setBackground(Color.green);
}
}
if(a.equals("yellow")){
for(int i=0;i<24;i++) {
s[i].setBackground(Color.yellow);
}
}
if(a.equals("blue")){
for(int i=0;i<24;i++) {
s[i].setBackground(Color.blue);
}
}
if(a.equals("red")){
for(int i=0;i<24;i++) {
s[i].setBackground(Color.red);
}
}
if(a.equals("gray")){
for(int i=0;i<24;i++) {
s[i].setBackground(Color.gray);
}
}
if(a.equals("orange")){
for(int i=0;i<24;i++) {
s[i].setBackground(Color.orange);
}
}
if(a.equals("pink")){
for(int i=0;i<24;i++) {
s[i].setBackground(Color.pink);
}
}
}
}
//编译按钮监听 加关于按钮监听
public void actionPerformed(ActionEvent e){
String s=e.getActionCommand();
Object source=e.getSource();
if(source==about){
// JOptionPane.showConfirmDialog(this, "软件1181张三 版权所有 侵权必究\n本计算器", "我的计算器", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, "DC Phoenix 版权所有 侵权必究", "我的计算器", JOptionPane.DEFAULT_OPTION);
//
}
}
class CopyListener implements ActionListener { //拷贝数据处理
public void actionPerformed(ActionEvent event) {
StringSelection contents=new StringSelection(textField.getText()); //用拷贝文本框
//文本实例化StringSelection对象
clipboard.setContents(contents,null); //设置系统剪贴板内容
}}
class PasteListener implements ActionListener { //拷贝数据处理
public void actionPerformed(ActionEvent event) {
Transferable contents= clipboard.getContents(this); //得到剪贴板内容
if(contents!=null &&contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
//判断内容是否为空,是否为字符串
try{
String string= (String) contents.getTransferData(DataFlavor.stringFlavor);
//转换内容到字符串
textField.setText(string); //插入字符串到粘贴文本框
}catch (Exception ex){
ex.printStackTrace(); //错误处理
}}
//设置系统剪贴板内容
}}
private void myEvent()
{
//打开菜单项监听
openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
openDia.setVisible(true); //显得打开文件对话框
String dirpath = openDia.getDirectory();//获取打开文件路径并且保存
String fileName = openDia.getFile();//获取文件名并且保存
if(dirpath == null || fileName == null) //判断路径和文件是否为空
return ;
else
textField.setText(null); //文件不为空 清楚原来文件内容
file = new File(dirpath, fileName); //创建新的路径和名称
try {InputStreamReader bu = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader bufr = new BufferedReader(bu);//尝试从文件中读东西
String line = null; //变量字符串初始化为空
while((line = bufr.readLine())!= null)
textField.setText(line+"\r\n"); //显示每一行内容
bufr.close();//关闭文件
}catch(FileNotFoundException e1) {
e1.printStackTrace(); // 抛出文件路径找不到异常
}catch(IOException e2){
e2.printStackTrace();// 抛出IO异常
}
}
});
saveItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (file == null) {
saveDia.setVisible(true);//显示保存文件对话框
String dirpath = saveDia.getDirectory();//获取保存文件路径并保存到字符串中。
String fileName = saveDia.getFile();获取打保存文件名称并保存到字符串中
if (dirpath == null || fileName == null)//判断路径和文件是否为空
return;//空操作
else
file=new File(dirpath,fileName);//文件不为空,新建一个路径和名称
}
try {
BufferedWriter bufw = new BufferedWriter(new FileWriter(file));
String text = textField.getText();//获取文本内容
bufw.write(text);//将获取文本内容写入到字符输出流
bufw.close();//关闭文件
}catch (IOException e1) {
e1.printStackTrace();//抛出IO异常
}
}
});
//窗体关闭监听
//退出菜单项监听
closeItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public String calculate(String s)throws myException{
char sign='+';
double rea=0;
double d=0;
int top=0;
int j=1;
int c=0;
double small=0;
String result=" ";
double temp=0;
double [] stack=new double[s.length()];
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if((ch>='0'&&ch<='9')){
d=(d*10.0-'0'+ch);
}
if(ch=='Π'){
d=Math.PI;
}
if((i==s.length()-1)||(ch<'0'&&ch!=' ')||(ch=='^'||ch=='%'||ch=='√'||ch=='.'||ch=='D'||ch=='!')){
if(sign=='+'){
stack[++top]=+d;
}
if(sign=='-'){
stack[++top]=-d;
}
if(sign=='^'){
temp=Math.pow(stack[top],d);
stack[top]=temp;
}
if(sign=='D'){
temp=1/stack[top];
stack[top]=temp;
}
if(sign=='!'){
for( int h=1;h<=stack[top];h++){
j*=h;
}
stack[top]=j;
}
if(sign=='%'){
temp=stack[top]%d;
stack[top]=temp;
}
if(sign=='√'){
temp=Math.sqrt(d);
stack[top]=temp;
}
if(sign=='.'){
if(d<10){
c=1;
}
if(d>10){
c=2;
}
small=Math.pow(0.1,c);
temp=stack[top]+d*small;
stack[top]=temp;
}
if(sign=='*'){
temp=stack[top]*d;
stack[top]=temp;
}
if(sign=='/'){
if(d==0){
throw new myException("被除数不能为0");
}
else{
temp=stack[top]/d;
stack[top]=temp;
}
}
d=0.0;
sign=ch;
}
}
while(top!=-1)
rea+=stack[top--];
if ((int)rea == rea)
result=Integer.toString((int)rea);
else
result=Double.toString(rea);
// String result = String.valueOf(rea);
return result;
}
public static void main(String[] args) {
FlowWindow jk=new FlowWindow();
jk.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jk.setVisible(true);
jk.setTitle("计算器");
jk.pack();
jk.setBounds(500, 400, 500, 300);
}
}
java swing计算器(包括复制,粘贴与文件的打开与保存)
最新推荐文章于 2024-06-21 17:14:47 发布