如何用JAVA语言写一个计算器小程序?
导入javax . swing . *;
导入Java . awt . event . *;
导入Java . awt . *;
公共课计算器?扩展JFrame实现ActionListener?{
private JFrame jf
私有JButton[]all buttons;
私有JButton clearButton
二等兵JTextField jtf
公共计算器(){
//实例化一个图形组件
Jf=new JFrame("任静的计算器1.0: Java版");
JF . addwindowlistener(new window adapter(){
public void windowClosing(){
system . exit(0);
}
});?
all buttons = new JButton[16];
clear button = new JButton(" clear ");
jtf = new JTextField(25);
jtf . set editable(false);
String str="123+456-789*0。=/";
for(int I = 0;我& ltallButtons.lengthi++){
all buttons[I]= new JButton(str . substring(I,I+1));
}
}
public void init(){
//完成布局
JF . set layout(new BorderLayout());
JPanel north panel = new JPanel();
JPanel center panel = new JPanel();
JPanel south panel = new JPanel();
north panel . set layout(new flow layout());
center panel . set layout(new GridLayout(4,4));
south panel . set layout(new flow layout());
north panel . add(jtf);
for(int I = 0;我& lt16;i++){
center panel . add(all buttons[I]);
}
south panel . add(clear button);
jf.add(northPanel,BorderLayout。北);
jf.add(centerPanel,BorderLayout。中心);
jf.add(southPanel,BorderLayout。南);
add eventhandler();
}
//添加事件侦听
public void addEventHandler(){
jtf . addactionlistener(this);
for(int I = 0;我& ltallButtons.lengthi++){
所有按钮[i]。addActionListener(this);
}
clear button . addactionlistener(new action listener(){
public void action performed(action event e){
// TODO自动生成的方法存根
calculator . this . jtf . settext(" ");
}
});
}
//事件处理
public void action performed(action event e){
//在这里完成事件处理?让计算器运行起来
string action = e . getactioncommand();
if(action = = "+" | | action = = "-" | | action = = " * " | | action = = "/"){
}
}
public void setFontAndColor(){
字体f =新字体(“ì”,字体。粗体,24);
jtf . set font(f);
jtf.setBackground(新颜色(0x8f,0xa0,0x FB));
for(int I = 0;我& lt16;i++){
所有按钮[i]。set font(f);
所有按钮[i]。setForeground(颜色。红色);
}
}
public void showMe(){
init();
setFontAndColor();
JF . pack();
JF . set visible(true);
JF . setdefaultcloseoperation(JFrame。EXIT _ ON _ CLOSE);
}
公共静态void main(String[] args){
新计算器()。show me();
}
}