数组的下标界限(使用JFormattedTextField控件)
/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作 者: 臧鹏
* 完成日期: 2013 年 8月 16日
* 版 本 号: 001
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:利用eclipse的windowBuilder的编写的窗口程序,练习使用JFormattedTextField控件,通过接收用户的输入获得数组下标,找到对应的题目,显示出来。若是输入*
的下标过大会显示异常信息。
* 程序输出:
* 程序头部的注释结束
*/
package 第三章数组;
import java.awt.BorderLayout;
public class 数组的下标界限 extends JFrame {
private JPanel contentPane;
private JTextArea textArea;
private final JFormattedTextField formattedTextField = new JFormattedTextField(NumberFormat.getIntegerInstance());
/**
* Launch the application.
* 本例的关键点在于从文本框接收整型数据,这要考虑用户输入格式的问题,如果用户输入小数或者非数字的字符,这时程序还要进行一些
* 验证操作,这样比较费时,而且容易出错,不易维护,所以本例采用了JFormattedTextField文本框控件,这个控件在创建时的构造方法
* 中可以指定格式器类型,然后这个控件就只接受该类型的数据。通过NumberFormat.getIntegerInstance()方法获取整数格式对象
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
数组的下标界限 frame = new 数组的下标界限();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public 数组的下标界限() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("\u8DA3\u5473\u7B54\u9898");
lblNewLabel.setBounds(21, 31, 54, 15);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("\u9898\u53F7");
lblNewLabel_1.setBounds(21, 82, 54, 15);
contentPane.add(lblNewLabel_1);
formattedTextField.setBounds(96, 82, 205, 32);
contentPane.add(formattedTextField);
JButton btnNewButton = new JButton("\u9009\u62E9");
btnNewButton.addActionListener(new ActionListener() {
private String[] info = {"50元奖金","给大家唱首歌","学狗叫","3万元奖金","讲一个笑话"};
public void actionPerformed(ActionEvent e) {
//获取用户输入的整数
int index = ((Number)formattedTextField.getValue()).intValue();
try{
textArea.setText(info[index-1]);//获取指定下标的数组元素所对应的题号的内容显示到文本域控件中
}catch(Exception e2){
textArea.setText("发生异常:\n"+e2.toString());//异常信息显示在文本域控件中
}
}
});
btnNewButton.setBounds(331, 86, 93, 23);
contentPane.add(btnNewButton);
textArea = new JTextArea();
textArea.setBounds(21, 133, 403, 119);
contentPane.add(textArea);
}
}
还没有评论,来说两句吧...