java - why cannot read int value from JTextField
問(wèn)題描述
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); }}
問(wèn)題解答
回答1://導(dǎo)包。import javax.swing.*;import java.awt.event.*;
class JTextFieldDemo{
public static void main(String[] args){ JFrame jf = new JFrame();//創(chuàng)建窗體框架 jf.setTitle('我的標(biāo)題');//設(shè)置窗體標(biāo)題 jf.setBounds(400,500,300,200);//設(shè)置窗體在屏幕上出現(xiàn)的位置及大小 jf.setVisible(true);//設(shè)置窗體可見(jiàn)JPanel jp = new JPanel();//創(chuàng)建JPanel組件 jf.setContentPane(jp);//將JPanel組件添加到JFrame窗體中JButton jb = new JButton('轉(zhuǎn)到');//創(chuàng)建JButton按鈕組件 jp.add(jb);//將JButton組件添加到JPanel中JTextField jtf = new JTextField(10);//創(chuàng)建JTextField jp.add(jtf);//將JTextField添加到JPanel中 jb.addActionListener(new ActionListener()//給JButtona按鈕添加點(diǎn)擊事件 {public void actionPerformed(ActionEvent e){ String a =jtf.getText(); int IntA = Integer.parseInt(a); System.out.println(IntA);} });}
}
綜上所述:樓主出現(xiàn)如上問(wèn)題是因?yàn)閖tf.getText();方法應(yīng)該在輸入內(nèi)容后才讓它執(zhí)行,而樓主所示的代碼卻讓它在運(yùn)行時(shí)就執(zhí)行,所以會(huì)報(bào)錯(cuò)。(個(gè)人拙見(jiàn),嘿嘿)
回答2:謝謝@Sjs_k 的答案
把 JTextField t1 = new JTextField(''); 改去 JTextField t1 = new JTextField(5); 就行了
相關(guān)文章:
1. android - webview 自定義加載進(jìn)度條2. 為什么我ping不通我的docker容器呢???3. javascript - 微信小程序限制加載個(gè)數(shù)4. linux - openSUSE 上,如何使用 QQ?5. mysql - 怎么讓 SELECT 1+null 等于 16. python 怎樣用pickle保存類(lèi)的實(shí)例?7. 并發(fā)模型 - python將進(jìn)程池放在裝飾器里為什么不生效也沒(méi)報(bào)錯(cuò)8. 大家好,請(qǐng)問(wèn)在python腳本中怎么用virtualenv激活指定的環(huán)境?9. linux - 升級(jí)到Python3.6后GDB無(wú)法正常運(yùn)行?10. Python中, 仿照經(jīng)典代碼實(shí)現(xiàn)單例, 卻出現(xiàn)了不是單例的的狀態(tài), 代碼哪里出錯(cuò)了 ?
