如何添加到以前的 JLabel

How to add to a previous JLabel

我已经更改了代码,所以它可能更容易解释,现在是我试图解决的初始问题。我首先创建一个 JLabel,然后尝试通过添加新行然后添加更多文本来更新其中包含的文本。我看过类似的问题,但解决方案没有帮助。这是一个时间表应用程序。

private void createAndShowGUI(String [] lessons) {

...

Container pane = frame.getContentPane();
GridBagConstraints c = new GridBagConstraints();
...

label1 = new JLabel("");
    label1.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0.0;
    c.gridwidth = 3;
    c.gridx = 2;
    c.gridy = 2;
    pane.add(label1, c);

for(int i=0; i<lessons.length; i++) {
        String format = lessons[i];
        String [] t = format.split(",");
        if (t[0].equals("1")) {
            if (t[1].equals("1")) {
                label1.setText(label1.getText() + "lecture: " + t[3] + " unit: " + t[4] + " room: " + t[2]);

...

现在,如果我不更改其他地方写入的变量,我的输入将保持不变。我当前的输入是 lessons[0] = "1,1,1,taqi,maths,bob", lessons[1] = "1,1,2,john,physics,jim" 还有一些其他的,但他们不相关,因为它们最终都处于相同的情况。

在 label1.setText 中,我试图在 label1.getText()"lecture: " 之间添加一个新行。所以当我 运行 我的代码时,我有一个讲座、单元和房间,下面我有另一个讲座、单元和房间。现在为了更清楚地了解我的输出,t[0] 是讲座的日期,t[1] 是讲座的时间。我正在尝试在同一时间段和同一天在不同房间显示多个课程。

JLabel 无法识别换行符。文本单行显示,换行符被忽略。

您可以在 JLabel 中使用 HTML:

label.setText("<html>line1<br>line2</html");

或者您可以使用 JTextArea 并附加多行文本:

textArea.append("\nline2");

我没有正确使用 HTML 代码。我发现我必须将 "<html>" 保留在文本输入的最开头(即 JPanel 的初始输入),即使我稍后向它添加了更多文本,并且 "</html>" 就在字符串的结尾。 "<br>" 可以在字符串中的任何地方使用。

修改后的代码:

JLabel label1 = new JLabel("<html>");

...

for(int i=0; i<lessons.length; i++) {
        String format = lessons[i];
        String [] t = format.split(",");
        if (t[0].equals("1")) {
            if (t[1].equals("1")) {
                label1.setText(label1.getText() + "lecture: " + t[3] + " unit: " + t[4] + " room: " + t[2] + "<br>");

                ...
            }
        }
} 
label1.setText(label1.getText() + "</html>");