簡體   English   中英

在TextArea中顯示文件內容

[英]Display file contents in a TextArea

好的,所以我將嘗試使其盡可能地易於理解。

我創建了一個帶有“打開”按鈕和textArea的簡單GUI(以及其他內容,但現在不重要)。 基本上,我正在創建一種方法,當我單擊“打開”按鈕時,它將在textArea中顯示文件的內容。

我相信我編寫的方法中有99%是正確的,但我一直收到NullPointerException,但我不太明白為什么。 希望我的代碼可以消除對我所問問題的任何困惑,我將在出現異常的代碼行中進行注釋。 這是我的代碼:

應用程序類(我的GUI的基本設置):

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

public class Application extends JFrame {

public OutputPanel outPanel = new OutputPanel();
public BarcodePanel barPanel = new BarcodePanel();
public ButtonPanel btnPanel = new ButtonPanel();
public ReferencePanel refPanel = new ReferencePanel();

public Application() {
super("Book Processor");
this.setLayout(new BorderLayout());

btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
outPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
refPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

add(btnPanel, BorderLayout.NORTH);
add(outPanel, BorderLayout.WEST);
add(refPanel,BorderLayout.SOUTH);
}//end constructor

public static void main(String[] args) {
Application frame = new Application();
frame.setSize(1000,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}//end main

}//end class

下一組代碼是我的ButtonPanel類(這是我遇到的問題),所以我有一個openFile method ,當我單擊按鈕時,它應該在textArea中顯示文件的內容。 再次,我收到NullPointerException,我不明白為什么。 這是此類的代碼:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class ButtonPanel extends JPanel{


JButton btnOpen = new JButton("Open");
OutputPanel outPanel = new OutputPanel();
Scanner input;

public ButtonPanel() {
ButtonHandler handler = new ButtonHandler();

add(btnOpen);
btnOpen.addActionListener(handler);

}//end constructor


 /**
  * Method for displaying the file onto the textArea.
  * 
  */
private void openFile() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);


int result = chooser.showOpenDialog(this);

String fileName;

fileName = chooser.getSelectedFile().getAbsolutePath();

try {
    Scanner input = new Scanner(Paths.get(fileName));
    StringBuilder sb = new StringBuilder();

    while(input.hasNextLine()) {

        sb.append(input.nextLine()+ "\n");

    }

    outPanel.txtOutput.setText(sb.toString());//my issue is with this line right here

} catch (IOException e) {

    e.printStackTrace();
}
finally {
    input.close();
}

}//end readFile



private class ButtonHandler implements ActionListener{

public void actionPerformed(ActionEvent e) {

    if(e.getSource()== btnOpen) {

        openFile();

    }

}//end actionPerformed


}//end actionlistener


}//end class

這是我的最后一個類OutputPanel ,該類包含JTextArea:

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JTextArea;

public class OutputPanel extends JPanel{

public JTextArea txtOutput = new JTextArea(20,50);

public OutputPanel() {

add(txtOutput);

}//end constructor

}//end class

如何獲取textArea以顯示文件的內容? 更重要的是,為什么我會收到此異常以及如何解決該異常? 希望這盡可能地有意義,我真的很感謝你們的任何投入。

您的NullPointerException實際上是由

} finally {
    input.close();
}

因為inputnull (很顯然)。 這是因為您在try-catch塊中隱藏了變量

try {
    Scanner input = new Scanner(Paths.get(fileName));
    //...
} finally {
    // This is null because the instance field has not been initialised
    input.close();
}

更好的解決方案是利用try-with-resources語句

try (Scanner input = new Scanner(Paths.get(fileName))) {
    StringBuilder sb = new StringBuilder();

    while (input.hasNextLine()) {

        sb.append(input.nextLine() + "\n");

    }

    outPanel.txtOutput.setText(sb.toString());//my issue is with this line right here

} catch (IOException e) {
    e.printStackTrace();
}

更好的解決方案是利用JTextArea讀取Reader內容的功能,例如...

try (FileReader reader = new FileReader(chooser.getSelectedFile())) {
    outPanel.txtOutput.read(reader, fileName);
} catch (IOException e) {
    e.printStackTrace();
}

現在,在詢問為什么文本區域中沒有內容之前,原因是因為您在ButtonPanel類中創建了OutputPanel的新實例,這與您在Application創建並添加到屏幕的實例沒有關系。

您將需要(通過構造函數)將OutputPanel的實例OutputPanelButtonPanel ,以使引用匹配。

就個人而言,一個更好的解決方案是定義一個interface ,該interface具有一個采用Fileread方法。 OutputPanel將實現此interfaceButtonPanel將需要對該interface的實例的引用。 OutputPanel代碼解耦,並防止ButtonPanelOutputPanel進行不必要的更改-因為這樣做不是真正的責任-加載文件並顯示它是OutputPanel的責任

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM