java - 将 BufferedReader 插入 JTextArea

标签 java swing jtextfield bufferedreader

不知道是否有人可以帮助我。作业将在大约 3 小时后到期,我非常沮丧。我无法让正在阅读的文件显示在 JTextArea 中。这就是我需要做的。有人可以帮忙吗?

public class Reader extends javax.swing.JFrame {

/**
 * Creates new form Reader
 */
public Reader() {
    initComponents();
}

public void displayText(){
    JLabel Text = new JLabel();
    add(Text);
}
/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
    jLabel1.setText("Contact Info");

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    jTextArea1.setEditable(false);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(54, 54, 54)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 477, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(71, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(176, 176, 176))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(25, 25, 25)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(64, 64, 64))
    );

    pack();
    setLocationRelativeTo(null);
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) throws IOException {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Reader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Reader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Reader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Reader.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            String everything = sb.toString();
        } finally {
            br.close();
        }          


    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Reader().setVisible(true);

        }
    });
}

// Variables declaration - do not modify                    
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration                  
}

最佳答案

移动

BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}         

进入类构造器,public Reader() {,然后使用 jTextArea1.setText(sb.toString()) 将文本应用到 JTexArea

public Reader() {
    initComponents();
    BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        jTextArea1.setText(sb.toString())
    } finally {
        br.close();
    }         
}

话虽如此,你并没有真正很好地管理你的资源,考虑使用更像......的东西

try (BufferedReader myReader = new BufferedReader(new FileReader("file1.txt"))) {
    String text = null;
    while ((text = myReader.readLine()) != null) {
        jTextArea1.append(text + "\n");
    }
} catch (IOException exp) {
    exp.printStackTrace();
}

或者更简单的...

try (Reader myReader = new BufferedReader(new FileReader("file1.txt"))) {
    jTextArea1.read(myReader, "Inventory");
} catch (IOException exp) {
    exp.printStackTrace();
}

关于java - 将 BufferedReader 插入 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29090115/

相关文章:

java - 在java中使用JButton向客户端发送消息

java - 仅当多个 JTextField 不为空时才保存

java - JTextField:将十进制逗号重新映射到点

java - 在代码中而不是在 hibernate.cfg.xml 中添加实体映射

java - 在java中通过返回类型重载方法

java - Fork/Join 结合 FileChannel 来复制文件

java - JTextField,使用Document Filter过滤整数和句号

java - 此 OutputStream 代码不会将字符串保存到 Txt 文件中

java - 如何将 JPanel 及其组件另存为 JPEG

Java小程序: actionlistener of button with noname