簡體   English   中英

讀取包含多行的文件並將其輸出到JLabel

[英]Reading a file that has multiple lines and outputting that to a JLabel

我正在從一個包含成千上萬行文本的文件中讀取內容,我希望程序讀取該文件中的所有行並將它們以相同格式輸出到JLabel或任何可行的文件上。

public String readSoldTo() {
        String file = "/Users/tylerbull/Documents/JUUL/Sold To/soldTo.txt";
        String data;

        try{

            BufferedReader br = new BufferedReader(new FileReader(file));

            while ((data = br.readLine()) != null) {
                System.out.println(data);
                return data;

                }
              br.close();
              }catch(Exception e) {

              }
        return file;
    }

構建JLabel來顯示一行文本。 是的,您可以對它進行評審以顯示更多內容,但這很麻煩,並且經常會在代碼中引起將來的問題。 相反,我建議您在JTextArea中顯示文本,並且可以通過使其背景顏色為空來刪除其邊框來使其看起來像JLabel。 如果將其添加到JScrollPane中,則會看到滾動條(如果適用)和滾動窗格的邊框,這可能是一個問題。 我還將再次使JTextArea不可聚焦和不可編輯,以使其表現得更像標簽,而不像接受用戶交互的文本組件。

此外,像JTextFields一樣,JTextComponents也具有允許您向其傳遞閱讀器的機制,以便它可以參與文本文件的讀取,並在需要時保留換行符。 有關更多信息,請參見其讀取方法API條目 與往常一樣,請注意遵守Swing線程規則,並在后台線程中執行文本I / O,並在Swing事件線程上進行所有Swing突變調用。

您的代碼也讓我有些擔心:

  • 您似乎忽略了例外
  • 上面的方法中有兩個返回值,並且都返回兩個截然不同的信息。

例如:

import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

@SuppressWarnings("serial")
public class TextAreaAsLabel extends JPanel {
    private static final int TA_ROWS = 30;
    private static final int TA_COLS = 50;
    private static final Font TA_FONT = new Font(Font.DIALOG, Font.BOLD, 12);
    private JTextArea textArea = new JTextArea(TA_ROWS, TA_COLS);

    public TextAreaAsLabel() {
        // JButton and JPanel to open file chooser and get text
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(new JButton(new ReadTextAction("Read Text")));

        // change JTextArea's properties so it "looks" like a multi-lined JLabel
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setBackground(null);
        textArea.setBorder(null);
        textArea.setFocusable(false);
        textArea.setEditable(false);
        textArea.setFont(TA_FONT);

        // add components to *this* jpanel
        setLayout(new BorderLayout());
        add(textArea, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.PAGE_END);
    }

    private class ReadTextAction extends AbstractAction {
        public ReadTextAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            // create file chooser and limit it to selecting text files
            JFileChooser fileChooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
            fileChooser.setFileFilter(filter);
            fileChooser.setMultiSelectionEnabled(false);

            // display it as a dialog
            int choice = fileChooser.showOpenDialog(TextAreaAsLabel.this);
            if (choice == JFileChooser.APPROVE_OPTION) {

                // get file, check if it exists, if it's not a directory
                File file = fileChooser.getSelectedFile();
                if (file.exists() && !file.isDirectory()) {
                    // use a reader, pass into text area's read method
                    try (BufferedReader br = new BufferedReader(new FileReader(file))){
                        textArea.read(br, "Reading in text file");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Foo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new TextAreaAsLabel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

暫無
暫無

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

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