数组的下标界限(使用JFormattedTextField控件)

快来打我* 2024-04-17 05:50 102阅读 0赞
  1. /* (程序头部注释开始)
  2. * 程序的版权和版本声明部分
  3. * Copyright (c) 2011, 烟台大学计算机学院学生
  4. * All rights reserved.
  5. * 文件名称:
  6. * 作 者: 臧鹏
  7. * 完成日期: 2013 年 8月 16日
  8. * 版 本 号: 001
  9. * 对任务及求解方法的描述部分
  10. * 输入描述:
  11. * 问题描述:利用eclipse的windowBuilder的编写的窗口程序,练习使用JFormattedTextField控件,通过接收用户的输入获得数组下标,找到对应的题目,显示出来。若是输入*
  12. 的下标过大会显示异常信息。
  13. * 程序输出:
  14. * 程序头部的注释结束
  15. */
  16. package 第三章数组;
  17. import java.awt.BorderLayout;
  18. public class 数组的下标界限 extends JFrame {
  19. private JPanel contentPane;
  20. private JTextArea textArea;
  21. private final JFormattedTextField formattedTextField = new JFormattedTextField(NumberFormat.getIntegerInstance());
  22. /**
  23. * Launch the application.
  24. * 本例的关键点在于从文本框接收整型数据,这要考虑用户输入格式的问题,如果用户输入小数或者非数字的字符,这时程序还要进行一些
  25. * 验证操作,这样比较费时,而且容易出错,不易维护,所以本例采用了JFormattedTextField文本框控件,这个控件在创建时的构造方法
  26. * 中可以指定格式器类型,然后这个控件就只接受该类型的数据。通过NumberFormat.getIntegerInstance()方法获取整数格式对象
  27. */
  28. public static void main(String[] args) {
  29. EventQueue.invokeLater(new Runnable() {
  30. public void run() {
  31. try {
  32. 数组的下标界限 frame = new 数组的下标界限();
  33. frame.setVisible(true);
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. });
  39. }
  40. /**
  41. * Create the frame.
  42. */
  43. public 数组的下标界限() {
  44. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  45. setBounds(100, 100, 450, 300);
  46. contentPane = new JPanel();
  47. contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  48. setContentPane(contentPane);
  49. contentPane.setLayout(null);
  50. JLabel lblNewLabel = new JLabel("\u8DA3\u5473\u7B54\u9898");
  51. lblNewLabel.setBounds(21, 31, 54, 15);
  52. contentPane.add(lblNewLabel);
  53. JLabel lblNewLabel_1 = new JLabel("\u9898\u53F7");
  54. lblNewLabel_1.setBounds(21, 82, 54, 15);
  55. contentPane.add(lblNewLabel_1);
  56. formattedTextField.setBounds(96, 82, 205, 32);
  57. contentPane.add(formattedTextField);
  58. JButton btnNewButton = new JButton("\u9009\u62E9");
  59. btnNewButton.addActionListener(new ActionListener() {
  60. private String[] info = {"50元奖金","给大家唱首歌","学狗叫","3万元奖金","讲一个笑话"};
  61. public void actionPerformed(ActionEvent e) {
  62. //获取用户输入的整数
  63. int index = ((Number)formattedTextField.getValue()).intValue();
  64. try{
  65. textArea.setText(info[index-1]);//获取指定下标的数组元素所对应的题号的内容显示到文本域控件中
  66. }catch(Exception e2){
  67. textArea.setText("发生异常:\n"+e2.toString());//异常信息显示在文本域控件中
  68. }
  69. }
  70. });
  71. btnNewButton.setBounds(331, 86, 93, 23);
  72. contentPane.add(btnNewButton);
  73. textArea = new JTextArea();
  74. textArea.setBounds(21, 133, 403, 119);
  75. contentPane.add(textArea);
  76. }
  77. }

Center Center 1

发表评论

表情:
评论列表 (有 0 条评论,102人围观)

还没有评论,来说两句吧...

相关阅读