java - 将文件打开到JLabel中

标签 java file jlabel

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

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

最佳答案

是的,这是有可能的,但是正如已经提到的,使用JTextArea或类似的组件会好得多,并且很可能为您省去了一些麻烦。

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


一个标题;
换行符;
缩进;
左边缘填充;
线包装;
粗体,斜体,下划线;
字体,字体样式,字体大小,甚至字体颜色;
文本对齐方式,例如Left,Center,Right和Justify;
等等等等


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

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


最终,您的JLabel将如下所示:

enter image description here

注意,在上面的代码行中,字符串文本以<html>开头,以</html>结尾。这两个标签之间的任何文本都被认为是用HTML换行的。您还将注意到字符串中的<br>标记,该标记强制换行以创建两行。

JLabel的功能非常有限,没有HTML,它实际上无法执行上面列出的任何项目符号,并且无法在JLabel中显示文本文件,如下所示:

enter image description here

您当然会注意到上图中的滚动条。 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属性为空(无);
复制displayFileInJLabel()方法并将其粘贴到
交通便利的地方。如果您愿意,可以在JFrame Form类中执行。
在以下位置调用displayFileInJLabel()方法
JFrame的ComponentResized事件,如下所示:

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


最好让类成员变量保存文件路径以进行查看,而不是对其进行硬编码,然后将该成员变量填充在具有String Type参数的Form的Class Constructor中。


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

关于java - 将文件打开到JLabel中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55251112/

相关文章:

java - 如何为 Google map 设置特定中心?

Java Geoip2 : Getting "java.lang.reflect.InvocationTargetException" Exception

java - SQL连接: can't connect to database in java

java - Jlabel无法显示int

java - log4j append=false 对我不起作用……为什么?

Python:从 .txt 文件中读取行并用它们进行计算

c - Win32 API CopyFile() 无法发送多个文件

Python 检查文件是否存在,如果存在则更新它,否则创建它

java - 翻转存储卡游戏的卡片在 java 中不起作用(没有小程序)

java - 使用 KeyListeners 更好地进行 JLabel 移动