/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* 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);
}
}
數組的下標界限(使用JFormattedTextField控件)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.