编写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 WPF 大屏看板表格背景图片设置
- ¥15 这个主板怎么能扩出一两个sata口
- ¥15 不是,这到底错哪儿了😭
- ¥15 2020长安杯与连接网探
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
- ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
- ¥16 mybatis的代理对象无法通过@Autowired装填
- ¥15 可见光定位matlab仿真
- ¥15 arduino 四自由度机械臂
- ¥15 wordpress 产品图片 GIF 没法显示