m0_69078841 2022-06-05 14:37 采纳率: 100%
浏览 55
已结题

java gui求1-n的和

编写GUI程序,用户在图形界面输入任意n,计算得出1+2+…+n的值

  • 写回答

2条回答 默认 最新

  • sinJack 2022-06-05 14:45
    关注

    我给你写下

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class SumFrame extends JFrame implements ActionListener {
        private static final long serialVersionUID = -3059616600875760053L;
        JLabel lable, labTotal;
        JTextField textLable, textTotal;
        static JButton butSummation;
        public SumFrame() {
            lable = new JLabel("輸入n");
            labTotal = new JLabel("前n项和");
            textLable = new JTextField("", 10);
            textTotal = new JTextField("", 10);
            butSummation = new JButton("计算");
            lable.setBounds(30, 30, 120, 30);
            textLable.setBounds(180, 30, 120, 30);
            labTotal.setBounds(30, 130, 120, 30);
            textTotal.setBounds(180, 130, 120, 30);
            butSummation.setBounds(160, 180, 120, 30);
            add(lable);
            add(textLable);
            add(labTotal);
            add(textTotal);
            add(butSummation);
            setLayout(null);
            setBounds(200, 100, 400, 300);
            // 窗口在屏幕中间显示
            setLocationRelativeTo(null);
            setTitle("求总量");
            setResizable(false);
            setVisible(true);
        }
        public static void main(String[] args) {
            SumFrame summationForm = new SumFrame();
            butSummation.addActionListener(summationForm);
            summationForm.add(butSummation);
        }
        public void actionPerformed(ActionEvent e) {
            JButton jb = (JButton) e.getSource();
            if (jb == butSummation) {
                String Mathematics = textLable.getText();
                try {
                    int a = Integer.parseInt(Mathematics);
                    int sum=0;
                    for(int i=1;i<=a;i++){
                        sum+=i;
                    }
                    textTotal.setText(String.valueOf(sum));
                } catch (Exception e2) {
                    JOptionPane.showMessageDialog(this, "输入的格式错误!", "提示对话框", JOptionPane.DEFAULT_OPTION);
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月13日
  • 已采纳回答 6月5日
  • 创建了问题 6月5日