使JTable单元格完美方形

问题描述

是否有任何机制可以使JTable的单元格完全正方形?目前,我只是在表格的实现中覆盖此方法

#ifndef FILESYstemMODEL_H
#define FILESYstemMODEL_H

#include <QFileSystemModel>
#include <QMimeDatabase>
#include "libs/global.h"
#include "libs/imagecachehelper.h"

class FileSystemModel : public QFileSystemModel {
     Q_OBJECT
  public:
     FileSystemModel(QString dataPath);

     // qabstractitemmodel interface
  public:
     QMimeDatabase mimeDb;
     QVariant data(const QModelIndex& index,int role) const;
     QFileInfo getFileInfo(const QModelIndex& index);

  private:
     static const int COLUMN_ICON = 0;
     static const int COLUMN_FILENAME = 1;
     static const int COLUMN_LOCATION = 2;
     static const int COLUMN_DATE_MODIFIED = 3;
     static const int COLUMN_SIZE = 4;

     QString dataPath;
     QLocale locale;

     // qabstractitemmodel interface
  public:
     QVariant headerData(int section,Qt::Orientation orientation,int role) const;

     // qabstractitemmodel interface
  public:
     int columnCount(const QModelIndex& parent) const;
};

#endif // FILESYstemMODEL_H

这在大多数情况下都可以正常工作,如下面的图片我有一个15x15的JTable:

enter image description here

但是,如果我扩展了JPanel,则表位于宽度方向,单元格将继续沿宽度和长度方向扩展,从而导致下面的3行被切除:

enter image description here

我想知道是否有更好的解决方案来使JTable的单元格完全正方形?

解决方法

根据我的评论,如果宽度或高度较小(限制因素),则需要使用一些逻辑来计算。然后根据哪个较小,您可以更改单元格的大小。

我不是建议对行高使用覆盖,而是尝试弄乱JTable componentResized事件,而是简单地设置所需的大小,而不是尝试对列覆盖进行弄乱。在此示例中,我假设单元格的数量固定为(15x15):

int rowCount = 15;
int colCount = 15;

your_JTable.addComponentListener(new ComponentAdapter(){

    @Override
    public void componentResized(ComponentEvent e){
        //Get new JTable component size
        Dimension size = getSize();
        
        int cellSize;

        //Check if height or width is the limiting factor and set cell size accordingly
        if (size.height / rowCount > size.width / colCount){
            cellSize = size.width / colCount;
        }
        else{
            cellSize = size.height / rowCount;
        }
        
        //Set new row height to our new size
        setRowHeight(cellSize);
        
        //Set new column width to our new size
        for (int i = 0; i < getColumnCount(); i++){
            getColumnModel().getColumn(i).setMaxWidth(cellSize);
        }
    }
});

在水平或垂直或两者同时调整大小时,这在JDK13中提供了完美的正方形单元。我意识到我也回答了您的previous question,因此这是使用该代码的有效示例:

enter image description here