用Swing写的一个计算器的例子(转贴)

在此我把源代码整个贴上来,有利于初学者学习哦。

//标准型计算器
package standardCalculator;

import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.text.*;


public class Calculator1 extends JPanel implements ClipboardOwner{
 
 
  // declarations of all used components
  public JFrame theFrame;
  public JLabel memoryLabel;
  public JMenuBar theMenuBar;
  public JMenu editMenu;
  public JMenuItem copyMenuItem, pasteMenuItem;
  public JMenu viewMenu;
  public ButtonGroup styleButtonGroup;
  public JRadioButtonMenuItem staRBMenuItem, sciRBMenuItem;
  public JCheckBoxMenuItem chooseNumberGroup;
  public JMenu helpMenu;
  public JMenuItem helpMenuItem, aboutMenuItem;
  public ActionListener copyListener, pasteListener;
  public ActionListener styleListener, chooseListener;
  public ActionListener helpListener, aboutListener;
  public ActionListener buttonListener;
  public JTextField theTextField;
  public GridBagConstraints gbc;
 
 
  public Clipboard clipboard = getToolkit().getSystemClipboard();
  public int flagSTART = 1;
  public int flagCE = 0;
  public Double memoryStore = new Double(0);
  public double result = 0;
  String operator = "NULL";
  public String theDisplay = new String();
 
 
  public Calculator1(){
   
  }
 
 
  public Calculator1(boolean on){
   gbc = new GridBagConstraints();
   
   // creating the JFrame, JMenuBar, JTextField, JPanel
   theFrame = new JFrame("Calculator");
   theMenuBar = new JMenuBar();
   theTextField = new JTextField();
   theTextField.setHorizontalAlignment(JTextField.RIGHT);
    theTextField.setText("0.");
   
   
    // creating the menus and menu items
    editMenu = new JMenu("Edit");
    copyMenuItem = new JMenuItem("Copy");
    pasteMenuItem = new JMenuItem("Paste");
    pasteMenuItem.setEnabled(false);
    //===============================================================
    viewMenu = new JMenu("View");
    styleButtonGroup = new ButtonGroup();
    staRBMenuItem = new JRadioButtonMenuItem("Standard");
    sciRBMenuItem = new JRadioButtonMenuItem("Scientific", true);
    styleButtonGroup.add(staRBMenuItem);
    styleButtonGroup.add(sciRBMenuItem);
    //---------------------------------------------------------------
    chooseNumberGroup = new JCheckBoxMenuItem("NumberGroup");
    //===============================================================
    helpMenu = new JMenu("Help");
    helpMenuItem = new JMenuItem("Help Contents...");
    aboutMenuItem = new JMenuItem("About Calculator...");
   
   
    // creating JLabel
    memoryLabel = new JLabel("");
    memoryLabel.setBorder(BorderFactory.createBevelBorder(1));

   
    // creating the action listeners
    copyListener = new CopyListener();
    pasteListener = new PasteListener();
    //===============================================================
    styleListener = new StyleListener();
    //---------------------------------------------------------------
    chooseListener = new ChooseListener();
    //===============================================================
    helpListener = new HelpListener();
    aboutListener = new AboutListener();
    //===============================================================
    buttonListener = new ButtonListener();   
   
   
    // connecting components to the action listeners
    copyMenuItem.addActionListener(copyListener);
    pasteMenuItem.addActionListener(pasteListener);
    //===============================================================
    staRBMenuItem.addActionListener(styleListener);
    sciRBMenuItem.addActionListener(styleListener);
    //---------------------------------------------------------------
    chooseNumberGroup.addActionListener(chooseListener);
    //===============================================================
    helpMenuItem.addActionListener(helpListener);
    aboutMenuItem.addActionListener(aboutListener);
    //===============================================================
    ContainerListener listener = new ContainerAdapter() {
      public void componentAdded(ContainerEvent e) {
     Component comp = e.getChild();
     if (comp instanceof JButton) ((JButton)comp).addActionListener(buttonListener);
      }
    };
    addContainerListener(listener);
   
   
    // creating Mnemonics for MenuItems and RadioButtonMenuItems
    editMenu.setMnemonic(KeyEvent.VK_E);
    copyMenuItem.setMnemonic(KeyEvent.VK_C);
    pasteMenuItem.setMnemonic(KeyEvent.VK_P);
    //===============================================================
    viewMenu.setMnemonic(KeyEvent.VK_V);
    staRBMenuItem.setMnemonic(KeyEvent.VK_T);
    sciRBMenuItem.setMnemonic(KeyEvent.VK_S);
    //---------------------------------------------------------------
    chooseNumberGroup.setMnemonic(KeyEvent.VK_G);
    //===============================================================
    helpMenu.setMnemonic(KeyEvent.VK_H);
    helpMenuItem.setMnemonic(KeyEvent.VK_H);
    aboutMenuItem.setMnemonic(KeyEvent.VK_A);   
   
   
    // creating Accelerators for MenuItems and RadioButtonMenuItems
    copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(
      KeyEvent.VK_C, InputEvent.CTRL_MASK, false));
    pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(
      KeyEvent.VK_V, InputEvent.CTRL_MASK, false));
     
     
    // setting tooltips
    memoryLabel.setToolTipText("Memory setting flag");
   
   
    // adding components to menus
    editMenu.add(copyMenuItem);
    editMenu.add(pasteMenuItem);
    //===============================================================
    viewMenu.add(staRBMenuItem);
    viewMenu.add(sciRBMenuItem);
    viewMenu.addSeparator();
    //---------------------------------------------------------------
    viewMenu.add(chooseNumberGroup);
    //===============================================================
    helpMenu.add(helpMenuItem);
    helpMenu.addSeparator();
    helpMenu.add(aboutMenuItem);
   
   
    // adding menus to JMenuBar
    theMenuBar.add(editMenu);
    theMenuBar.add(viewMenu);
    theMenuBar.add(helpMenu);
   
   
    // adding components to JFrame
   gbc.weightx = 1.0; 
    gbc.weighty = 1.0;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridwidth = 6;
    addGB(this, theMenuBar, 0, 0);
    addGB(this, theTextField, 0, 1);
    //添加数字JButton
    gbc.gridwidth = 1;
    for(int row=5; row>2; row--)
   for(int column=1; column<4; column++)
     addGB(this, new JButton("  "+(15+column-3*row)+"  "), column, row);
 //添加其它JButton
    addGB(this, new JButton("0"), 1, 6);
    addGB(this, new JButton("+/-"), 2, 6);
    addGB(this, new JButton("."), 3, 6);
    addGB(this, new JButton("+"), 4, 6);
    addGB(this, new JButton("-"), 4, 5);
    addGB(this, new JButton("×"), 4, 4);
    addGB(this, new JButton("÷"), 4, 3);
    addGB(this, new JButton("="), 5, 6);
    addGB(this, new JButton(" 1/x "), 5, 5);
    addGB(this, new JButton("%"), 5, 4);
    addGB(this, new JButton("√ ̄"), 5, 3);
    addGB(this, new JButton("C"), 2, 2 );
    addGB(this, new JButton("CE"), 3, 2);
    gbc.gridwidth = 2;
    addGB(this, new JButton("Backspace"), 4, 2);
    gbc.gridwidth = 1;
    gbc.ipadx = 50;
    addGB(this, memoryLabel, 0, 2);
    gbc.ipadx = 0;
    addGB(this, new JButton("MC"), 0, 3);
    addGB(this, new JButton("MR"), 0, 4);
    addGB(this, new JButton("MS"), 0, 5);
    addGB(this, new JButton("M+"), 0, 6);
  } // end of constructing Calculator1(boolean on) 
 
 
  public void addGB(Container cont, Component comp, int x, int y) {
    if ((cont.getLayout() instanceof GridBagLayout) == false)
             cont.setLayout(new GridBagLayout());
    gbc.gridx = x;
    gbc.gridy = y;
    cont.add(comp, gbc);
  }
 
  class CopyListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
     copy();
    }
  }
 
  public void copy(){
 String srcData = theTextField.getText();
 if(srcData != null){
   StringSelection contents = new StringSelection(srcData);                
    clipboard.setContents(contents, this);
   pasteMenuItem.setEnabled(true);
 }
  }
 
  class PasteListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
     paste();
    }
  }
 
  public void paste(){
 Transferable content = clipboard.getContents(this);
 if(content != null){
   try{
     String dstData = (String)content.getTransferData(DataFlavor.stringFlavor);
     theTextField.setText(dstData);
   }catch (Exception e){
     System.out.println("Couldn't get contents in format: "+
                                 DataFlavor.stringFlavor.getHumanPresentableName());
       }                   
 }
  }
 
  class StyleListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
    
    }
  }

  class ChooseListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
      NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
      if(chooseNumberGroup.getState() == true){
       double operand = Double.parseDouble(theDisplay);
       ((DecimalFormat)numberFormat).setGroupingSize(3);
       numberFormat.setGroupingUsed(true);
       theTextField.setText(new Double(numberFormat.format(operand)).toString());
      }
     else numberFormat.setGroupingUsed(false);
    }
  }
   
  class HelpListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
   
    }
  }
 
  class AboutListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
   
    }
  }

  class ButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
     if(e.getActionCommand().trim().equals("C")){
       theDisplay = "0.";
       theTextField.setText(theDisplay);
       result = 0;
       flagSTART = 1;
       return;
     }
     else if(e.getActionCommand().trim().equals("CE")){
      flagCE = 1;
      theDisplay = "0.";
       theTextField.setText(theDisplay);
       flagSTART = 1;
       return;
     } 
      else if(e.getActionCommand().trim().equals("Backspace")){
       int lengeth = theDisplay.length();
       if(lengeth > 1){
         theTextField.setText(theDisplay.substring(0,lengeth-1));
          return;
        }
        theTextField.setText("");
        return;
     } 
      else if(e.getActionCommand().trim().equals("MS")){
      memoryLabel.setText("M");
      memoryLabel.setVerticalAlignment(JLabel.CENTER);
      memoryLabel.setHorizontalAlignment(JLabel.CENTER);
       memoryStore = Double.valueOf(theDisplay);
       return;
     }
     else if(e.getActionCommand().trim().equals("MC")){
      memoryLabel.setText("");
      memoryStore = new Double(0);
      return;
     }
      else if(e.getActionCommand().trim().equals("MR")){
       theDisplay = memoryStore.toString();
       theTextField.setText(theDisplay);
       return;
     }
     else if(e.getActionCommand().trim().equals("M+")){
      memoryStore = new Double(memoryStore.doubleValue()
        + Double.parseDouble(theDisplay));
      return;    
     }
      else if(e.getActionCommand().trim().equals("+/-")){
        theDisplay = new Double(0.0 - Double.parseDouble(theDisplay)).toString();
        theTextField.setText(theDisplay);
     return;
      }
      else if(e.getActionCommand().trim().equals("1/x")){
        theDisplay = new Double(1.0 / Double.parseDouble(theDisplay)).toString();
     theTextField.setText(theDisplay);
     return;
      }
     else if(e.getActionCommand().trim().equals("√ ̄")){
       theDisplay = new Double(Math.sqrt(Double.parseDouble(theDisplay))).toString();
       theTextField.setText(theDisplay);
       return;
     }
     else if(e.getActionCommand().trim().equals("%")){
       theDisplay = new Double(Double.parseDouble(theDisplay) / 100.0).toString();
       theTextField.setText(theDisplay);
       return;
     }
     else if(!isOperator(e.getActionCommand().trim())){
      if(flagSTART == 1){
        flagCE = 0; 
         theDisplay = e.getActionCommand().trim();
         theTextField.setText(theDisplay);
         flagSTART = 0;
         return;
       }
      theDisplay = theDisplay + e.getActionCommand().trim();
        theTextField.setText(theDisplay);
        return;
     }
     // is operator
     if(flagCE == 1){
      flagCE = 0;
      operator = e.getActionCommand().trim();
      return;
     } 
     else if(operator.equals("NULL")||operator.equals("=")){
      result = Double.parseDouble(theDisplay);
     }
     else if(operator.equals("+")){
       result = result + Double.parseDouble(theDisplay);
     }
     else if(operator.equals("-")){
      result = result - Double.parseDouble(theDisplay);
     } 
     else if(operator.equals("×")){
     result = result * Double.parseDouble(theDisplay);
     }
     else if(operator.equals("÷")){
      result = result / Double.parseDouble(theDisplay);
     }
     flagSTART = 1;
     operator = e.getActionCommand().trim();
     theDisplay = new Double(result).toString();
     theTextField.setText(theDisplay);
     return;
    }
  }
 
 
  boolean isOperator(String operator){
   if(operator.equals("+")||operator.equals("-")||operator.equals("×")
                           ||operator.equals("÷")||operator.equals("=")) return true;
   else return false;
  }


  public void lostOwnership(Clipboard clipboard, Transferable contents){
    System.out.println("Clipboard contents replaced");
  }

 
  private void launchFrame(){
   //JFrame theFrame = new JFrame("Calculator");
 theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 theFrame.setSize(420,220);
    theFrame.setLocation(100,100);
    theFrame.setContentPane(new Calculator1(true));
    theFrame.setVisible(true);
  }
 
  public static void main(String[] args){
    Calculator1 calculator1 = new Calculator1(true);
    calculator1.launchFrame();   
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值