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. css3 - css怎么實現圖片環繞的效果2. 對mysql某個字段監控的功能3. showpassword里的this 是什么意思?代表哪個元素4. mysql優化 - mysql EXPLAIN之后怎么看結果進行優化 ?5. html - vue項目中用到了elementUI問題6. JavaScript事件7. javascript - 原生canvas中如何獲取到觸摸事件的canvas內坐標?8. css3 - border-bottom 的長度可否超過盒子的寬度呢?實現如下圖效果。(我的書下面的線)9. mysql scripts提示 /usr/bin/perl: bad interpreter10. python - 為什么正常輸出中文沒有亂碼,zip函數之后出現中文編程unicode編碼的問題,我是遍歷輸出的啊。
