java - why cannot read int value from JTextField
問題描述
JTextField t1 = new JTextField(' ');String a = t1.getText(); int intA = Integer.parseInt(a); System.out.println(intA);
Error
java.lang.NumberFormatException: For input string: '1 '
附上我的代碼
public class Testing extends JPanel { public int s; public Testing() {JPanel p = new JPanel();JTextField t1 = new JTextField(' ');JTextField t2 = new JTextField(' ');JTextField t3 = new JTextField(' ');JButton b3 = new JButton('result');p.add(t1);p.add(t2);p.add(t3);p.add(b3);add(p);b3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {try { String a = t1.getText(); int intA = Integer.parseInt(a); System.out.println(intA); // String b = t2.getText(); //t3.setText(a+'');} catch (NumberFormatException ignored) { System.out.println(ignored);} }}); } public static void main(String... arg) {Testing p = new Testing();JFrame frame = new JFrame();frame.add(p);frame.setLocationRelativeTo(null);frame.pack();frame.setVisible(true); }}
問題解答
回答1://導包。import javax.swing.*;import java.awt.event.*;
class JTextFieldDemo{
public static void main(String[] args){ JFrame jf = new JFrame();//創建窗體框架 jf.setTitle('我的標題');//設置窗體標題 jf.setBounds(400,500,300,200);//設置窗體在屏幕上出現的位置及大小 jf.setVisible(true);//設置窗體可見JPanel jp = new JPanel();//創建JPanel組件 jf.setContentPane(jp);//將JPanel組件添加到JFrame窗體中JButton jb = new JButton('轉到');//創建JButton按鈕組件 jp.add(jb);//將JButton組件添加到JPanel中JTextField jtf = new JTextField(10);//創建JTextField jp.add(jtf);//將JTextField添加到JPanel中 jb.addActionListener(new ActionListener()//給JButtona按鈕添加點擊事件 {public void actionPerformed(ActionEvent e){ String a =jtf.getText(); int IntA = Integer.parseInt(a); System.out.println(IntA);} });}
}
綜上所述:樓主出現如上問題是因為jtf.getText();方法應該在輸入內容后才讓它執行,而樓主所示的代碼卻讓它在運行時就執行,所以會報錯。(個人拙見,嘿嘿)
回答2:謝謝@Sjs_k 的答案
把 JTextField t1 = new JTextField(''); 改去 JTextField t1 = new JTextField(5); 就行了
相關文章:
1. android-studio - Android Studio 運行項目的時候一堆警告,跑步起來!?2. dockerfile - [docker build image失敗- npm install]3. mysql - 新浪微博中的關注功能是如何設計表結構的?4. angular.js使用$resource服務把數據存入mongodb的問題。5. 如何解決Centos下Docker服務啟動無響應,且輸入docker命令無響應?6. angular.js - 關于$apply()7. MySQL數據庫中文亂碼的原因8. 表單提交驗證,沒反應,求老師指點9. nignx - docker內nginx 80端口被占用10. angular.js - Ionic 集成crosswalk后生成的apk在android4.4.2上安裝失敗???
