Search code examples
javaswingjlabel

How to add to a previous JLabel


I have changed the code, so it might be a bit simpler to explain, and is now the initial problem I was trying to solve. I create a JLabel at first and I am then trying to update the text contained within it, by adding a new line and then adding more text. I have taken a look at similar questions, but the solutions did not help. This is for a timetable application.

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]);

...

Now, my input stays the same if I do not change the variables that are written else where. My current input is lessons[0] = "1,1,1,taqi,maths,bob", lessons[1] = "1,1,2,john,physics,jim" and there are a few others, but they are not relevant as they all end up in the same situation.

Within the label1.setText, I am trying to add a new line between label1.getText() and "lecture: ". So that when I run my code, I have a lecture, unit and room, and below I have another lecture, unit and room. Now for a clearer picture of my output, t[0] is the Day of the lecture and t[1] is the Time of the lecture. I am trying to display multiple lessons in different rooms on the same period and day.


Solution

  • A JLabel doesn't recognize new line characters. The text is displayed on a single line and the new line character is ignored.

    You can use HTML in a JLabel:

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

    Or you can use a JTextArea and append multiple lines of text:

    textArea.append("\nline2");