【问题标题】:Reading a file that has multiple lines and outputting that to a JLabel读取具有多行的文件并将其输出到 JLabel
【发布时间】:2016-10-13 21:32:38
【问题描述】:

我正在读取一个包含大量文本行的文件,我希望我的程序读取该文件中的所有行,并将它们以相同的格式输出到 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;
    }

【问题讨论】:

    标签: java swing file-io jlabel


    【解决方案1】:

    JLabel 用于显示一行文本。是的,您可以对其进行陪审以显示更多内容,但这是一个杂项,并且通常会在您的代码中导致未来的问题。相反,我建议您在 JTextArea 中显示您的文本,您可以通过将其背景颜色设为 null 来移除其边框,使其 看起来 像 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());
        }
    }
    

    【讨论】:

    • 我在读取数据时遇到问题。当我在另一个类中调用该方法时,它说它为空。我需要什么,所以当我用另一种方法调用它时,它将拥有所有数据?
    • @TylerBull:参见上面的示例代码。您的新问题是一个完全不相关的问题,您必须进行调试。回头看看你的代码,看看为什么你在你不期望的地方得到了 null 。如果需要,请使用调试器。
    • 我搞定了。我使用了 JTextArea 并附加了一个数组来显示我的文本。感谢您的帮助。
    • @TylerBull:请查看someone answers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2019-07-17
    • 2022-01-21
    相关资源
    最近更新 更多