【问题标题】:.read ERROR: cannot find symbol symbol: method read(bufferedreader,<null>) location: variable jtext1 of type jbutton.read 错误:找不到符号符号:方法 read(bufferedreader,<null>) 位置:jbutton 类型的变量 jtext1
【发布时间】:2019-11-25 19:10:17
【问题描述】:
private void jtext1ActionPerformed(java.awt.event.ActionEvent evt)
{                                       

    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();
    String filename = f.getAbsolutePath();

    try
    {
        FileReader reader = new FileReader(filename);
        BufferedReader br = new BufferedReader(reader);
        jtext1.read(br, null);
        br.close();
        jtext1.requestFocus();
    }
    catch (Exception e)
    {
        JOptionPane.showMessageDialog(null, e);
    }
}                

我在为应用程序创建功能时尝试在 JButton 中运行此代码并不断收到错误消息:

找不到符号符号:方法 read(bufferedreader,) 位置:jbutton 类型的变量 jtext1

【问题讨论】:

  • 你到底想在这里做什么?阅读 JTextField 组件的内容? jtext 到底是什么?
  • 我正在尝试从计算机上的任何文本文件中读取 a ,而 jtext1 是我在 JFrame 中创建的按钮的名称,应该允许我这样做。

标签: java compiler-errors


【解决方案1】:

您收到该错误是因为您从 JButton 调用 read() 方法,但按钮不读取文件——它们所做的只是在单击它们时引发事件,以便您可以运行其他响应代码。

您应该做的是在br 上调用read(),这是您的BufferedReader。我不确定您为什么要尝试将 BufferedReader 的实例传递给它自己,但这些不是 read() 采用的参数。即使您在正确的对象上调用该方法,它也会失败并出现不同的错误。

通常,您会使用readLine() 方法,顾名思义,该方法读取整行文本,允许您逐行处理文件,而无需告诉您的代码需要多少字节的数据每次读取都进行处理。

你想做这样的事情:

private void jtext1ActionPerformed(java.awt.event.ActionEvent evt)
{
    // Your FileChooser code should live in a separate method. If the user
    // selects the FileChooser from a menu, then create an event handler for
    // that menu item. 
    try
    {
        FileReader reader = new FileReader(filename);
        BufferedReader br = new BufferedReader(reader);

        String line = "";

        while((line = br.readLine()) != null)
        {
            // Do whatever you want with the line.
            // You can add it to an arraylist
            // or you can split() it into parts
            // or you can just print it to screen. Whatever.
        }
        br.close();
        // this line is probably unnecessary, but ultimately, not harmful
        jtext1.requestFocus();
    }
    catch (Exception e)
    {
        JOptionPane.showMessageDialog(null, e);
    }
}

【讨论】:

  • 谢谢,我会试一试,告诉你进展如何
猜你喜欢
  • 1970-01-01
  • 2016-04-30
  • 2019-04-10
  • 2014-12-12
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多