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. javascript - webpack1和webpack2有什么區別?2. thinkPHP5中獲取數據庫數據后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙3. django - Python error: [Errno 99] Cannot assign requested address4. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?5. python小白,關于函數問題6. javascript - vscode alt+shift+f 格式化js代碼,通不過eslint的代碼風格檢查怎么辦。。。7. python小白 關于類里面的方法獲取變量失敗的問題8. Python2中code.co_kwonlyargcount的等效寫法9. [python2]local variable referenced before assignment問題10. python - vscode 如何在控制臺輸入
