有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java读取具有多行的文件并将其输出到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;
    }

共 (1) 个答案

  1. # 1 楼答案

    JLabel用于显示一行文本。是的,您可以对其进行修改以显示更多内容,但这是一个混乱的问题,并且常常会在您的代码中导致将来的问题。相反,我建议您将文本显示在JTextArea中,您可以通过将背景色设为空来删除边框,使其看起来像JLabel。但是,如果将其添加到JScrollPane,您将看到滚动条(如果合适)和滚动窗格的边框,这可能是一个问题。我还将使JTextArea不可聚焦和不可编辑,这样它的行为更像一个标签,而不像接受用户交互的文本组件

    此外,JTextComponents(如JTextFields)具有允许您向其传递读取器的机制,以便它可以参与文本文件的读取,并在需要时保留换行符。有关这方面的更多信息,请参阅其read method API entry。和往常一样,注意遵守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());
        }
    }