我有grid
(JTable
),看起来像MS Excel
的网格。我想允许用户调整行和列的大小。对于列,我只是使用了这个:
grid.getTableHeader().setResizingAllowed(true);
对于行,我从here获取了TableRowResizer
类,我正在使用这个类:
new TableRowResizer(grid);
这很好用。但是,我有一个问题:在调整行大小时,行标题也不会调整大小。
以下是我如何制作行标题:
AbstractListModel lm = null;
lm = new TableListModel(grid);
final JList list = new JList(lm);
list.setFixedCellWidth(60);
list.setFixedCellHeight(grid.getRowHeight());
list.setCellRenderer(new TableRowHeaderRenderer(grid));
list.setBackground(grid.getTableHeader().getBackground());
scrollPane.setRowHeaderView(list);
这是TableRowHeaderRenderer
类:
class TableRowHeaderRenderer extends JLabel implements ListCellRenderer {
private JTable table;
public TableRowHeaderRenderer(JTable table)
{
this.table = table;
JTableHeader header = table.getTableHeader();
setOpaque(true);
setBorder(BorderFactory.createEtchedBorder());
setHorizontalAlignment(CENTER);
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
}
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus)
{
Color bg = UIManager.getColor("TableHeader.background");
int selectedrow = table.getSelectedRow();
if (selectedrow==index) bg = new Color(107, 142, 35);
setBackground(bg);
setText("" + Grid.getRowName(index));
return this;
}
}
这是TableListModel
类:
class TableListModel extends AbstractListModel{
private JTable mytable;
public TableListModel(JTable table) {
super();
mytable = table;
}
public int getSize() {
return mytable.getRowCount();
}
public Object getElementAt(int index) {
return "" + index;
}
}
答案 0 :(得分:2)
查看Row Number Table。它使用JTable(而不是JList)来呈现行号。因此,您可以将行高保持与主表同步。
但是,当主表的行高更改时,我无法自动重绘行标题,因为更改单个行高时不会触发任何事件。因此,您还需要修改调整大小代码,如下所示:
table.setRowHeight(resizingRow, newHeight);
JScrollPane scrollPane = (JScrollPane)SwingUtilities.getAncestorOfClass(JScrollPane.class, table);
scrollPane.getRowHeader().repaint();