创建具有多个列标题和行标题的自定义TableModel [英] Creating a custom TableModel with multiple column headers and row headers

查看:109
本文介绍了创建具有多个列标题和行标题的自定义TableModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个看起来像下面的模型的JTable:

I'm attempting to create a JTable that looks like the mockup below:

绿色角基本上是红色列和行标题的缓冲区.单元并不需要以图片中的颜色进行渲染.但是它们需要与表格中其余的白色"单元格区分开.

The green corner is basically buffer-space for the red column and row headers. The cells don't need to be rendered in the colours pictured; however they need to be distinguishable from the rest of the 'white' cells in the table.

此表也是不可编辑或不可选择的;它仅在更新时由用户查看.

This table also is not editable or selectable; it's merely viewed by a user whilst it is updated.

我知道这可以通过使用DefaultTableModel以及第1,2&&行的自定义呈现器来实现列1,2,并在设置和获取表值时加+2(计算用作标题的行和列).

I know this can be achieved using a DefaultTableModel with custom renders for rows 1,2 && cols 1,2 and adding +2 when setting and getting table values (accounting for the rows and columns that are being used as headers).

  1. 是否有一种更干净的方法来执行此操作,而又不使用标头中使用的这些静态值来污染我的表模型?
  2. 我已经阅读了有关扩展表模型的信息,但是不确定是否应该扩展哪个类(DefaultTableModel,AbstractTableModel)以及应该重写的方法.

推荐答案

输入限制为20x20,因此包括标头为22x22.

Input is limited to 20x20 so including the headers that's 22x22.

还要考虑一个JScrollPane,它包含一个具有GridLayoutJPanel并包含22x22个实例JLabel,或者是一个合适的子类.这样可以轻松扩展到数千个单元格.

Also consider a JScrollPane containing a JPanel having GridLayout and containing 22x22 instances JLabel, or a suitable subclass. This scales easily to several thousand cells.

附录:如果需要,CellRendererPane可以作为一个很好的 flyweight 渲染器,建议此处.

Addendum: If the need arises, CellRendererPane makes a good flyweight renderer, as suggested here.

如果您选择JTable来呈现可伸缩性,

If you go with JTable for rendering scalability,

  1. 这不是滥用行为;正是打算使用TableModel的方式. TableModel为您确定的矩形矩阵建模. JTable只是该模型的一个(有效渲染的)视图.

  1. This is no abuse; it is exactly how TableModel is intended to be used. TableModel models a rectangular matrix of whatever you decide. JTable is just an (efficiently rendered) view of that model.

我更喜欢AbstractTableModel,如此处所示,因为Vector很少是所需的数据结构.使用任何使索引最方便的容器. DefaultTableModel很方便,并用作扩展AbstractTableModel的指南.特别是,您需要setValueAt().

I prefer AbstractTableModel, shown here, because Vector is rarely the desired data structure. Use whatever container makes your indexing most convenient. DefaultTableModel is handy and serves as a guide to extending AbstractTableModel. In particular, you'll need a setValueAt().

@Override
public void setValueAt(Object aValue, int row, int col) {
    ... // update your data structure
    this.fireTableCellUpdated(row, col); // notify the view
}

这篇关于创建具有多个列标题和行标题的自定义TableModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆