编写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); } } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 下图接收小电路,谁知道原理
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度
- ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
- ¥15 ETLCloud 处理json多层级问题
- ¥15 matlab中使用gurobi时报错
- ¥15 这个主板怎么能扩出一两个sata口
- ¥15 不是,这到底错哪儿了😭
- ¥15 2020长安杯与连接网探