当前位置: 代码迷 >> J2EE >> 自己写的第一个计算器, 用GUI生成的图形化界面解决思路
  详细解决方案

自己写的第一个计算器, 用GUI生成的图形化界面解决思路

热度:269   发布时间:2016-04-17 23:48:53.0
自己写的第一个计算器, 用GUI生成的图形化界面
用java做的计算器,可以求1到某个数之间所有数得和 
比如求1到100所有数的和是5050
1到1000所有数得和为50050.。。。。。。
下面是效果图。

package 小程序;
import java.awt.*;
import java.awt.event.*;
import java.io.File;


import javax.swing.*;
public class 求某个数以内所有整数的和 {
private Frame f=null;
private TextField tf1=null;
private TextField tf2=null;
private Button but1=null;
private Button but2=null;

private Dialog d=null;
private Label lab=null;
private Button okBut=null;

求某个数以内所有整数的和(){
init();
}
public void init(){
f=new Frame("求和计算器");
f.setBackground(null);
f.setBounds(200, 300, 400, 200);
//f.setLayout(new BoxLayout(f,2));
f.setLayout(new GridLayout(2,2));

but1=new Button("请输入你要求和的数");
tf1=new TextField(15);
tf1.setFont(new Font("宋体",Font.BOLD,72));//三个参数 第一个 可以到word里面查 第二个就是样式 比如粗体 斜体 什么的 这个API里面有
//第三个字体大小
but2=new Button("求这个数以内所有整数的和");
tf2=new TextField(15);
tf2.setFont(new Font("宋体",Font.BOLD,72));
tf2.setBackground(Color.YELLOW);


d=new Dialog(f,"错误提示",true);
d.setBounds(400,300,300,200);
d.setLayout(new FlowLayout());
lab=new Label();
okBut=new Button("确定");

d.add(lab);
d.add(okBut);


f.add(but1);
f.add(tf1);
f.add(but2);
f.add(tf2);

f.setVisible(true);
myEvent();
}
private void myEvent(){
f.addWindowListener((new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
}));
okBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
d.setVisible(false);
}
});
okBut.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER)
d.setVisible(false);
}
});
d.addWindowListener((new WindowAdapter(){
public void windowClosing(WindowEvent e){
d.setVisible(false);
}
}));
tf1.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
int code=e.getKeyCode();
if(code>=e.VK_0&&code<=e.VK_9||code==e.VK_BACK_SPACE){
//System.out.println(e.getKeyText(e.getKeyCode())+"是非法的");
}
else if(code==e.VK_ENTER){
String c1=tf1.getText();
int n1=Integer.parseInt(c1);

int count=0;
for(int i=n1;i>=0;i--){
count+=i;

}
String c=Integer.toString(count);
tf2.setText(c);
}
else{
e.consume();
String info="您输入的"+e.getKeyText(code)+"不是一个整数,请重新输入";
lab.setText(info);
d.setVisible(true);

};
}

});

but2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String c1=tf1.getText();
int n1=Integer.parseInt(c1);

int count=0;
for(int i=n1;i>=0;i--){
count+=i;

}
String c=Integer.toString(count);
tf2.setText(c);
}
});

}
public static void main(String[]args){
new 求某个数以内所有整数的和();
}
}




望大神指点。。。。。。。。。
------解决方案--------------------
楼主加油,建设把代码格式注意一下,
------解决方案--------------------
类名和包名是中文。。
------解决方案--------------------
恩,加油!!!
------解决方案--------------------
你描述的功能到是实现了,为什么不完善一下。
  相关解决方案