Search code examples
javaswingjtablenewlinetablecellrenderer

Newline (\n) is not working by using AbstractTableModel for JTable


I need to have multiple lines in one table column. I have given \r\n in between the String. But new line is not coming. I have tried with \n, System.lineSeparator() and line.separator. Nothing is working.

My output should allow multiple lines in each cell.

My Code shows as below:

import java.awt.BorderLayout;
import java.awt.Container;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

class AppSwing extends AbstractTableModel {



  public Object[][] values = {
      { "C\r\n\r\nAfterNewLine", "A\r\n\r\n" },
     };

  public int getRowCount() {
    return values.length;
  }

  public int getColumnCount() {
    return values[0].length;
  }

  public Object getValueAt(int row, int column) {
    return values[row][column];
  }
} 

Main class

import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JTable;

class App extends JFrame {

protected JTable table;

  public static void main(String[] args) {
    App stt = new App();
    stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    stt.setSize(400, 200);
    stt.setVisible(true);
  }

  public App() {
    Container pane = getContentPane();
    pane.setLayout(new BorderLayout());
    AppSwing tv = new AppSwing();
    table = new JTable(tv);
    pane.add(table, BorderLayout.CENTER);
  }

}

Result--

CAfterNewLine A


Solution

  • Try String Joiner as below example.

     String[] data = rowData.get(rowIndex);
                        StringJoiner joiner = new StringJoiner("<br>", "<html>", "</html>");
                        for (String text : data) {
                            joiner.add(text);
                        }
                        value = joiner.toString();