Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

java - How to display multiple lines in a JTable Cell

I would like to create a JTable like the below picture:enter image description here

Which java class will be used and possibly how?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Multiline JTable cell can make using a customized TableCellRenderer easily. Use following steps to create the TableCellRenderer.

Step 1: Create TableCellRenderer

Following code shows to create a multi-line TableCellRenderer for String[] values. It's possible to change the String[] into a Vector or an other Collection type

public class MultiLineTableCellRenderer extends JList<String> implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        //make multi line where the cell value is String[]
        if (value instanceof String[]) {
            setListData((String[]) value);
        }

        //cell backgroud color when selected
        if (isSelected) {
            setBackground(UIManager.getColor("Table.selectionBackground"));
        } else {
            setBackground(UIManager.getColor("Table.background"));
        }

        return this;
    }
}

Step 2: Set TableCellRenderer into the JTable

    MultiLineTableCellRenderer renderer = new MultiLineTableCellRenderer();

    //set TableCellRenderer into a specified JTable column class
    table.setDefaultRenderer(String[].class, renderer);

    //or, set TableCellRenderer into a specified JTable column
    table.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);

This is my tested screenshot:

Multi-line TableCellRenderer Test


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...