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. html5 - ElementUI table中el-table-column怎么設置百分比顯示。2. python - 使用readlines()方法讀取文件內容后,再用for循環遍歷文件與變量匹配時出現疑難?3. 對mysql某個字段監控的功能4. css3 - less或者scss 顏色計算的知識應該怎么學?或者在哪里學?5. 注冊賬戶文字不能左右分離6. javascript - table列過多,有什么插件可以提供列排序和選擇顯示列的功能7. css - 網頁div區塊 像蘋果一樣可左右滑動 手機與電腦8. javascript - 數組的過濾和渲染9. html - vue項目中用到了elementUI問題10. JavaScript事件
