java - why cannot read int value from JTextField

查看:66
本文介绍了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);
    }
}

解决方案

//导包。
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();方法应该在输入内容后才让它执行,而楼主所示的代码却让它在运行时就执行,所以会报错。(个人拙见,嘿嘿)

这篇关于java - why cannot read int value from JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆