java求和1到100之和
package count;
import java.awt.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import javax.swing.*;
public class count{
public static void main(String[] args) {
MyFrame mf=new MyFrame();
}
}
class MyFra extenmeds JFrame {
JTextField f;
JLabel L1;
JButton b1;
public MyFrame(){
this("count");
}
public MyFrame(String title){
super(title);
setSize(300,280);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
b1=new JButton("计算");
f=new JTextField("",11);
L1=new JLabel("1+2+???+100",JLabel.RIGHT);
b1.addActionListener((ActionListener) new()); inclass
add(L1);
add(b1);
add(f);
FlowLayout flow=new FlowLayout(FlowLayout.CENTER,18,20);
setLayout(flow);
center(this);
setVisible(true);
}
public void center(JFrame frame){
Toolkit toolkit=Toolkit.getDefaultToolkit();
Dimension dim=toolkit.getScreenSize();
int screenWidth=dim.width;
int screenHeight=dim.height;
int w=frame.getWidth();
int h=frame.getHeight();
int x=(screenWidth-w)/2;
int y=(screenHeight-h)/2;
frame.setLocation(x,y);
}
}
}
import javax.swing.*;
public class qiuhe {
public static void main(String[] args) {
MyFrame mf=new MyFrame();}
}
class MyFrame extends JFrame implements ActionListener {
JLabel L1;
JTextField T1;
JButton B1;
int sum=0;
public MyFrame(){
this("求和");
}
public MyFrame(String title){
super(title);
L1=new JLabel("1+2+3+。。。+100的和是:");
T1=new JTextField(10);
B1=new JButton("计算");
add(L1);
add(T1);
add(B1);
ionListener(this); B1.addAct
setSize(250,190);
FlowLayout flow=new FlowLayout(1,10,10);
setLayout(flow);
setBackground(Color.red);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
for(int i=1;i<=100;i++){
sum+=i;
}
if(e.getSource()==B1){
T1.setText(sum+"");
}
}
}