简体   繁体   中英

Default Table Model doesn't show new lines

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

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.

我以简单的方式做到了

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM