简体   繁体   中英

Reading a file that has multiple lines and outputting that to a JLabel

I am reading from a file that will have tons of lines of text and I want my program to read all of the lines in that file and output them in the same format onto either a JLabel or anything that would work.

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;
    }

A JLabel is built to display one line of text. Yes you can jury-rig it to show more, but that's a kludge and can often cause future problems in your code. Instead I would suggest that you display your text in a JTextArea, and you can make it so that it looks like a JLabel by removing its border by making its background color null. If you add it to a JScrollPane though, you'll see scrollbars (if appropriate) and the scrollpane's border, which may be a problem. I would also make the JTextArea non-focusable and non-editable, again so that it acts more like a label and less like a text component that accepts user interaction.

Also JTextComponents, like JTextFields have mechanisms that allow you pass it a reader so that it can participate in the reading of the text file, preserving line breaks if desired. Please see its read method API entry for more on this. As always, take care to respect Swing threading rules, and do your text I/O in a background thread, and all Swing mutation calls on the Swing event thread.

Your code also worries me some:

  • You seem to be ignoring exceptions
  • You have two returns in your method above, and both return two vastly different bits of information.

For example:

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM