久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

java - why cannot read int value from JTextField

瀏覽:112日期:2023-12-21 16:19:52

問題描述

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:

//導(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è)置窗體可見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)如上問題是因?yàn)閖tf.getText();方法應(yīng)該在輸入內(nèi)容后才讓它執(zhí)行,而樓主所示的代碼卻讓它在運(yùn)行時(shí)就執(zhí)行,所以會(huì)報(bào)錯(cuò)。(個(gè)人拙見,嘿嘿)

回答2:

謝謝@Sjs_k 的答案

把 JTextField t1 = new JTextField(''); 改去 JTextField t1 = new JTextField(5); 就行了

標(biāo)簽: java
相關(guān)文章:
主站蜘蛛池模板: 南皮县| 普兰店市| 湖南省| 新田县| 宜兴市| 玉门市| 临西县| 洪泽县| 江西省| 平潭县| 平顺县| 许昌县| 抚顺县| 瑞安市| 克拉玛依市| 深州市| 江口县| 东山县| 丰台区| 紫金县| 射阳县| 思南县| 桐城市| 郁南县| 富顺县| 曲阳县| 偃师市| 贺州市| 旬阳县| 黔西| 泰安市| 正安县| 灵山县| 民县| 汶川县| 汕尾市| 开化县| 清原| 克拉玛依市| 弥勒县| 项城市|