我想设计一个小程序,有一个按纽,一个文本框,当在文本框中输入一个数的时候,再点按纽,会在界面上显示这个数字的阶乘,多谢了。

解决方案 »

  1.   

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class example implements ActionListener{ JPanel top,bottom,mainPanel;
    JButton button;
    JTextField text;


    public example(){

    button = new JButton("button");


    text = new JTextField("请输入:");

    top = new JPanel();
    bottom = new JPanel();
    mainPanel = new JPanel(new GridLayout(2,1));

    top.setOpaque(true);
    bottom.setOpaque(true);

    top.add(button);

    bottom.add(text);

    mainPanel.setOpaque(true);
    mainPanel.add(top);
    mainPanel.add(bottom);

    button.addActionListener(this);



    }

    public void actionPerformed(ActionEvent e){
           int x = Integer.parseInt(text.getText());
           long z=1;
           if(x>0)   
           for (;x!=1;){
            z *= x;
            x--;
            
           }     text.setText("阶乘为" + z);
      }

    private static void createAndShowGUI(){

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    example contentPane = new example();
    contentPane.mainPanel.setOpaque(true);
    frame.setContentPane(contentPane.mainPanel);

    frame.pack();
    frame.setVisible(true);

    }

    public static void main(String[] args) {

    example.createAndShowGUI();
    }}
      

  2.   

    我也贴一个:
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends Frame implements ActionListener
    {
    static Test frm = new Test();
    static Button btn = new Button("点击求阶乘");
    static TextField tf = new TextField();
    static Label result = new Label("阶乘:");
    public static void main(String[] args)
    {
    frm.setTitle("阶乘");
    frm.setLayout(null);
    frm.setSize(400, 300);
    btn.setBounds(80, 80, 100,30);
    tf.setBounds(200, 80, 100, 30);
    tf.setFont(new Font("宋体", Font.PLAIN, 16));
    result.setBounds(200, 140, 100, 40);
    frm.add(btn);
    frm.add(tf);
    frm.add(result);
    frm.setVisible(true);
    frm.addWindowListener(new WindowAdapter()
    {
    public void windowClosing(WindowEvent e)
    {
    System.exit(0);
    }
    });
    btn.addActionListener(frm);
    tf.addActionListener(frm);
    }
    public int factorial(int l)
    {
    if(l < 0)
    return -1;
    else
    {
    int sum = 1;
    if(l == 0)
    return 0;
    else
    {
    for(int i = 1; i <= l; i++)
    sum *= i;
    }
    return sum;
    }
    }
    public void actionPerformed(ActionEvent e)
    {
    String str = tf.getText();
    int num = Integer.parseInt(str);
    int num2 = factorial(num);
    if(num2 < 0)
    result.setText("阶乘不存在");
    else
    result.setText("阶乘:"+ num2);
    }
    }