Question

Hi i want to show new line in DefaultTableModel but i dont know why table doesn't show enters. How to enable enters? If i have a string "stss\nsdd" it shows "stsssdd" but i want new line.

public class Main extends JFrame {

    DefaultTableModel model = new DefaultTableModel(
            new Object[][]{{"some", "text"}, {"any", "text"},
                {"even", "more"}, {"text", "str\nings"},
                {"and", "other"}, {"text", "values"}}, new Object[]{
                "Column 1", "Column 2"});

    public Main() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
        JTable table = new JTable(model);
        table.setRowHeight(40);
        getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
        pack();
    }

    public static void main(String arg[]) {
        new Main().setVisible(true);
    }
}
Was it helpful?

Solution 2

I did this in easy way

JLabel l = new JLabel("<html>Hello World!<br>blahblahblah</html>", SwingConstants.CENTER)

OTHER TIPS

That's because the DefaultTableCellRenderer uses JLabel as the component to paint the cells. And labels can't have new lines. You have to use your own TableCellRenderer that uses a TextComponent that accepts new lines, for example JTextArea.

final JTextArea textArea = new JTextArea(); // or static field
//...
table.setDefaultRenderer(Object.class, new TableCellRenderer()
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        textArea.setText(value.toString());
        return textArea;
    }

});

Try copying and pasting a text of a couple of lines, to see it work. Now you might want to cahnge the cellEditor and prevent the Enter key from finalizing the edition so it can be used to write new lines in the cells.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top