JTable细胞包裹

时间:2015-11-26 11:08:50

标签: text jtable

我想调整jtable中特定单元格的大小,以便在文本大小大于某个大小时自动设置。这就是我向我的表添加内容的方式。

        if(rs.next()) {

            rs.beforeFirst();
            Vector<String> columnNames = new Vector<String>();
            columnNames.add("Tweet");
            columnNames.add("Updated Time");

            Vector<Vector<Object>> data = new Vector<Vector<Object>>();

            while (rs.next()) {

                Vector<Object> vector = new Vector<Object>();
                Tweet = rs.getString(1);
                vector.add(Tweet);
                SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Timestamp time = rs.getTimestamp(2);
                Updated_time = sdf.format(time);
                vector.add(Updated_time);

                data.add(vector);
            }

            DefaultTableModel dfm = new DefaultTableModel(data, columnNames);

            JTable table = new JTable(dfm);
            table.setAutoscrolls(true);
            table.setShowGrid(false);

            ((DefaultTableCellRenderer)table.getDefaultRenderer(Object.class)).setOpaque(false);
            table.setOpaque(false);

2 个答案:

答案 0 :(得分:0)

public class MyRenderer extends JTextArea implements TableCellRenderer {

private static final long serialVersionUID = 1L;

public MyRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
setOpaque(true);
}

@Override
public Component getTableCellRendererComponent(JTable table, Object value,       boolean isSelected, boolean hasFocus,
    int row, int column) {
// TODO Auto-generated method stub
setText(value.toString());//or something in value, like value.getNote()..
if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
} else {
    setForeground(table.getForeground());
    setBackground(table.getBackground());
}
setSize(table.getColumnModel().getColumn(column).getWidth(),
    getPreferredSize().height);
if (table.getRowHeight(row) != getPreferredSize().height) {
    table.setRowHeight(row, getPreferredSize().height);
}
return this;
  }

}

答案 1 :(得分:0)

JTable单元实际上显示的是JLabel,因此对于文本换行,您可以应用html,如:

"<html>" + "Your value" + "<br>" + "Desc"