0

我一直在制作一个 GUI 程序,我正在调用一个引发异常的方法。我必须使用try and catch,因为我无法编辑代码,因为它的GUI。由于某种原因,代码不起作用。该代码应该获取文件的第一行并在标签中显示数字。这是代码:

    try{  
       String inputStr = JOptionPane.showInputDialog(this, "Enter The File Name: ");
       int x= codeReadFile(inputStr);
       String name= String.valueOf(x);
       chipCount.setText(name);
    }
    catch (IOException e) {
         JOptionPane.showMessageDialog(this,"No File");

    }    

文件读取程序的代码是:

      public static int codeReadFile (String filename) throws IOException, 
      FileNotFoundException {
      String line=null;
      int value=0;
      BufferedReader inputReader = new BufferedReader (new 
            InputStreamReader(new FileInputStream(filename)));
            while (( line = inputReader.readLine()) != null)
                value = Integer.parseInt(line);
                inputReader.close();
                return value;
4

2 回答 2

1

你说你想得到文件的第一行,但这段代码显然没有这样做:

while (( line = inputReader.readLine()) != null)
  value = Integer.parseInt(line);

它尝试读取整个文件并将每一行解析为int,丢弃除最后一个之外的所有值。你可能想说的是

line = inputReader.readLine();
return line != null? Integer.parseInt(line) : 0;

无论您的文件实际上是否只包含一行,您都应该拥有这样的代码。例如,如果文件包含一个额外的换行符,您将读取一个空行,尝试解析它,并得到一个NumberFormatException.

于 2012-12-11T19:45:07.853 回答
0

GUI 操作应始终在 EDT(事件调度线程)上调用。您可以通过将修改代码包装到某事中来实现这一点。喜欢:

SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                chipCount.setText(name);
            }
        });

否则可能会发生丑陋的事情;)

然后还有一种更简单的方法来检索BufferedReader. 只需删除流并使用 aFileReader代替。

最后一件事是:如果您的文件只包含一行,则只需读取一行。你正在做的是阅读所有行。如果最后一个为空,则您将得到错误的结果,甚至是 NumberFormatException by parseInt()

作为另一种方法,您可以在设置文本后尝试调用repaint()invalidate()在 chipCount 和/或其父级上。 编辑: 我刚刚读到你想在标签中显示它......然后重新绘制绝对是要走的路。您也可以只使用 aJTextField并使其不可编辑以摆脱它。

于 2012-12-11T19:19:19.983 回答