【问题标题】:Exception in thread "Thread-3" java.lang.NumberFormatException: For input string: ""线程“Thread-3”中的异常 java.lang.NumberFormatException:对于输入字符串:“”
【发布时间】:2014-03-08 22:03:48
【问题描述】:

所以我的主要计划是有一个带有一个按钮和两个jTextFields 的 GUI。当按下按钮时,它会启动我创建的 Runnah 类的新线程。假设Runnah 类从文本字段中获取输入;

当我运行 gui.getSeconds(); 时,Runnah 类会得到一个 NumberFormatException

MainGUI 类

public class MainGUI extends javax.swing.JFrame {

Runnah runnah;
Thread thread;

public MainGUI() {
    initComponents();
    //runnah = new Runnah();
}                        

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    try {
        runnah = new Runnah();
    } catch (AWTException ex) {
        Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    thread = new Thread(runnah);
    thread.start();
}                                           

public String getInput(){
    String temp = textInp.getText();
    return temp;
}
public int getSeconds(){
    return Integer.parseInt(secInp.getText());
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
                new MainGUI().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JTextField secInp;
private javax.swing.JButton startButton;
private javax.swing.JTextField textInp;
// End of variables declaration                   
}

Runnah 类

public class Runnah implements Runnable{

private MainGUI gui;

private Robot robot;

public Runnah() throws AWTException{
    this.robot = new Robot();
    gui = new MainGUI();
}

public Runnah(Robot robot) {
    this.robot = robot;
}

@Override
public void run() {

    String temp = gui.getInput();
    CharSequence input = temp;
    int seconds = 1;
    seconds = gui.getSeconds() * 1000;

    robot.delay(seconds);
}

如果需要更多信息,请告诉我。

【问题讨论】:

  • 此字段private MainGUI gui; 仍为null。你还没有初始化它。
  • 您正在从不是 EDT 的 Thread 访问 Swing 组件。这违反了 Swing 线程模型。违反线程模型可能会导致竞争风险、意外错误和(在极少数情况下)死亡。
  • 谢谢 Sotirios,我解决了这个问题。不过,它不会在几秒钟内从我的 textField 读取输入。现在说它是 "" 的字符串
  • 在这种情况下,我建议使用 final 关键字,以便编译器可以告诉您初始化问题。
  • 现在您似乎正在创建MainGUI 的新实例,而不是传入现有的实例。

标签: java swing jtextfield numberformatexception


【解决方案1】:

我只是没有引用现有的 MainGUI 类。

【讨论】:

    猜你喜欢
    • 2014-05-27
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多