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编辑过]