课外天地 李树青学习天地Java程序语言课件 → 简单计算器样本(自考机试)


  共有18943人关注过本帖树形打印复制链接

主题:简单计算器样本(自考机试)

帅哥哟,离线,有人找我吗?
admin
  1楼 博客 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信 管理员
等级:管理员 帖子:1945 积分:26736 威望:0 精华:34 注册:2003/12/30 16:34:32
简单计算器样本(自考机试)  发帖心情 Post By:2008/6/17 22:27:07 [只看该作者]

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator
{
        public static void main(String args[])
        {
                MyFrame m=new MyFrame("计算器");
                Toolkit theKit = m.getToolkit();
                Dimension wndSize = theKit.getScreenSize();
                
                m.setBounds(wndSize.width/4, wndSize.height/4, wndSize.width/2, wndSize.height/2);
                m.setVisible(true);
                m.pack();
        }
}

class MyFrame extends JFrame implements ActionListener
{
        JTextField jtf;
        JPanel jp;
        JButton[] jb;
        JButton jb1,jb2;
        int num1,num2;

        public MyFrame(String title)
        {
                super(title);  
                getContentPane().setLayout(new BorderLayout(0,0));
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                jtf=new JTextField();
                
                jp=new JPanel();
                jp.setLayout(new GridLayout(4,3));      
                jb=new JButton[10];
                jb1=new JButton("+");
                jb2=new JButton("=");
                
                for(int i=0;i<jb.length;i++)
                {
                        jb[i]=new JButton(String.valueOf(i));
                        jb[i].addActionListener(this);
                        jp.add(jb[i]);
                }
                
                jb1.addActionListener(this);
                jb2.addActionListener(this);
                jp.add(jb1);
                jp.add(jb2);
                
                getContentPane().add(jtf,BorderLayout.NORTH);
                getContentPane().add(jp,BorderLayout.CENTER);
        }
        
        public void actionPerformed(ActionEvent e)
        {
                JButton be=(JButton)e.getSource();
                String bt=be.getText();
                
                if(bt.equals("+"))
                {
                        num1=Integer.parseInt(jtf.getText());
                        jtf.setText("");
                }
                else if(bt.equals("="))
                {
                        num2=Integer.parseInt(jtf.getText());
                        jtf.setText(String.valueOf(num1+num2));
                }
                else
                {
                        jtf.setText(jtf.getText()+bt);
                }
        }
}

[此贴子已经被作者于2010-12-12 08:27:13编辑过]

 回到顶部