将文件打开到 JLabel

Opening a file into a JLabel

我想创建一个允许用户输入文件名的程序,然后它会在 JLabel 中显示文件中写入的所有内容,我已经设法 find/create 允许用户输入的代码文件的名称,然后在控制台中显示文件的内容,但我找不到一种方法来显示 JLabel 中文本文件中的所有内容。

有办法吗?正如一些人告诉我的那样,这是不可能的。

是的...这是可能的,但正如已经提到的那样,您最好改用 JTextArea 或类似组件,并且很可能会避免一些麻烦。

虽然 JLabel 基本上是为单行文本设计的,但它确实允许将该文本包装在 HTML 标记中,因此允许基本 HTML/CSS 格式化相同的文本。然后的诀窍是将所需文本文件的每一行读入一个字符串变量,在您附加读取的每一行时格式化该字符串,并且通过格式化,我的意思是添加:

  • 一个标题;
  • 换行;
  • 缩进;
  • 左边距填充;
  • 换行;
  • 粗体、斜体、下划线;
  • 字体、字体样式、字体大小,甚至字体颜色;
  • 左对齐、居中对齐、右对齐和两端对齐等文本对齐方式;
  • 等等,等等,等等

JLabel 无法识别您已经熟悉的常用换行符,例如 "\n""\r\n" 甚至 System.lineSeparator();。但是,它将处理 <br> 的 HTML 换行标记,但仅当应用于 JLabel 的文本包含在 HTML 中时才处理 。这是一个两行 JLabel 文本的示例:

String txt = "<html>This is line one.<br>This is line two.</html>";
jLabel1.setText(txt);

最终您的 JLabel 将如下所示:

注意在上面的代码行中,字符串文本以 <html> 开始并以 </html> 结束。这两个标签之间的任何文本都被视为 包裹在 HTML 中。您还会注意到字符串中的 <br> 标记,它强制换行以创建两行。

JLabel 的功能非常有限,如果没有 HTML,它实际上不能做上面列出的任何事情,也不能在 JLabel 中显示文本文件像这样:

你当然会注意到上图中的滚动条。 JLabel 的另一个问题是,如果需要,它不会显示滚动条。您需要将 JLabel 放入 JScrollPane 才能拥有此功能,因为很可能有些文件会超出 JLabel 的边界,因此您还需要考虑这一点。够简单,不是世界末日。

下面提供的方法将读取提供的文本文件并将其显示在提供的 JLabel 中。它会自动将所有内容包装成 HTML,提供标题,将所有文本左填充 10 像素,换行文本,处理换行符,并处理基本缩进:

public void displayFileInJLabel(JLabel label, String filePath) {
    try {
        // Try With Resources (will auto close the reader).
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            /* We use StringBuilder to build our HTML Wrapped 
               string to display within the JLabel.  */
            StringBuilder sb = new StringBuilder();

            // Get the width of our supplied JLabel
            int w = label.getWidth();

            /* Calculations for determininfg Line Wrap. 
               The (w / 4) is a modifiable offset.  */
            String width = String.valueOf((w - (w / 4))); 

            /* Deal with Line Wrap (JLabels don't do this) and
               set up Left Padding.  */
            sb.append("<html><body style='width: ").append(width).append("px; padding:10px;'>");

            /* Apply the Title Center of JLabel, Blue Color Text, 
               and Bold Font Style.The size of the text is determined 
               by the <h1> and </h1> tags.  */
            sb.append("<center><h1><font color=blue><b>").append(filePath).append("</b></font></h1></center><br>");

            // Read in File Lines one at a time.
            String line;
            while((line = reader.readLine()) != null) {
                /* Deal with multiple whitespaces (basic indenting etc) since HTML 
                   doesn't deal well with more than a single whitespace.  */
                line = line.replaceAll("\s{4}", "&nbsp;&nbsp;&nbsp;&nbsp;");

                /* Deal with line breaks. JLabels won't deal with them since 
                   it is designed for a single line of text. We therefore
                   apply the HTML Line Break tag (<br>)at the end of each 
                   text file line to take care of this business.   */
                line+= "<br>";

                sb.append(line);
            }

            // Apply the closing tags to finish our HTML Wrapping.
            sb.append("</body></html>");

            /* Set the formated HTML text to the JLabel */
            label.setText(sb.toString());
        }
    }
    catch (IOException ex) {
        Logger.getLogger("displayFileInJLabel() Method").log(Level.SEVERE, null, ex);
    }
}

如果您删除所有注释,那么代码确实不多,但还有更多工作要做。构建上面显示的表单示例

  • 创建一个新的 JFrame 窗体;
  • 将其 DefaultCloseOperation 属性 设置为 DISPOSE;
  • 将其 AlwaysOnTop 属性 设置为 true;
  • 在显示表单之前将其设置为 SetLocationRelativeTo 属性 到 null;
  • JScrollPane 放入 JFrame 窗体中。让它占据 表格的整个大小;
  • 将 JLabel 放入 JScrollPane 中。让它占据整个尺寸 JScrollPane 的;
  • 将 JLabel 的背景 颜色设置为白色;
  • 将 JLabel 的 Opaque 属性 设置为 true
  • 将 JLabel 的 Horizo​​ntalAlignment 设置为 LEFT;
  • 将 JLabel 的 VerticalAlighnment 设置为 TOP;
  • 确保 JLabel Text 属性 是 empty(无);
  • displayFileInJLabel() 方法复制并粘贴到 可访问的地方。如果您愿意,可以在您的 JFrame 表单中使用 Class。
  • 调用 displayFileInJLabel() 方法 JFrame 的 ComponentResized 事件,像这样:

    displayFileInJLabel(jLabel1, "C:\MyFiles\LoremIpsum.txt");
    

    最好让 class 成员变量保存要查看的文件路径,而不是对其进行硬编码,然后将此成员变量填充到具有字符串类型参数的表单的 Class 构造函数中。

这完全取决于您真正想做什么。使用 JTextArea 仍然是一个更好的主意。