自绘制多表头对应的tablemodel

本文介绍了一个名为MappingTableModel的Java类的设计与实现细节,该类继承了AbstractMappingModel,并用于处理表格数据。它实现了特定的数据填充逻辑,支持不同类型的列显示,并提供了用于编辑单元格值的方法。

import javax.swing.table.AbstractTableModel;

public abstract class AbstractMappingModel extends AbstractTableModel {

     /**
  *
  */
 private static final long serialVersionUID = 1L;
  protected Object[][] dataMesh = new Object[0][0];
    
     public abstract int getGroupColumnCounts();
    
     @Override
     public boolean isCellEditable(int row, int column) {
         return false;
     }

     public int getRowCount() {
         return dataMesh.length;
     }

     public Object getValueAt(int rowIndex, int columnIndex) {
         Object obj = dataMesh[rowIndex][columnIndex];
             return obj;
     }

     /**
      * get array name
      * @param idx array index not column index
      * @return
      */
     public abstract String getGroupColumnName(int idx);

     /**
      * get the sub column number
      * @param column the multiple table head index
      * @return
      */
     public abstract int getGroupColumnSubCounts(int column);

     /**
      * get the single table head number
      * @return
      */
     public abstract int getSingleColumnCount();

    

     /**
      * According array index convert the index
      * @param groupIndex
      * @param index
      * @return
      */
     public abstract int changeToTotalColumnIndex(int groupIndex, int index);
 }


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

import org.jdesktop.swingx.JXTable;

import com.alu.ieccf.editor.dict.EnumeratedShowTableModel;
import com.alu.ieccf.editor.dict.GroupedShowTableModel;
import com.alu.ieccf.editor.dict.ui.model.Table;
import com.alu.ieccf.editor.dict.utils.DictConfigureHelper;
import com.alu.ieccf.framework.messages.MessageKeyDict;
import com.cienet.jcore.resources.ResourceManagerImpl;

public class MappingTableModel  extends AbstractMappingModel{
   
    /**
  *
  */
 private static final long serialVersionUID = 1L;

 private String[] columns = new String[]{"CDR_Format_ID","Distribution_Config_ID"};

    private String[] singleColumns = {"Name","Type"};
    private String[] subColumnsCDR = {"XDR_ID","CDR_FormatID","Rule_ID","Encode_Dict_ID","Output_Encode_Type"};
    private String[] subColumnsDis = {"Distribution_Config_ID","Default_Destination","Default_Directory","Default_Extension","Destribution_Type"};
   

    private List<String> allColumns = new ArrayList<String>();
    private List<String> groupColumns = new ArrayList<String>();
    private List<Integer> groupChildSize = new ArrayList<Integer>();

 
    public static final int NAME = 0;
    public static final int TYPE = 1;
    public static final int ACTION_ENABLE = 2;
    public static final int GENERATE_PARTIAL_CDR = 3;

    private List<Mapping> mappingList;


    public MappingTableModel(){
        allColumns.clear();
        groupColumns.clear();
        groupChildSize.clear();
        mappingList = new ArrayList<Mapping>();


        for (String objects : singleColumns) {
            allColumns.add(objects);
        }

        for (int i = 0; i < columns.length; i ++) {
             String s = columns[i];
             if(i == 0){
                for (String obj : subColumnsCDR) {
                    allColumns.add(obj);
                 }
                groupColumns.add(s);
                groupChildSize.add(5);
                }else if(i == 1){
                    for (String obj : subColumnsDis) {
                        allColumns.add(obj);
                    }
                    groupColumns.add(s);
                    groupChildSize.add(5);
            }
        }
    }

     public int getSingleColumnWidth(int column){
        switch (column) {
            case NAME:
                return 200;
            case TYPE:
                return 150;
            default:
                return 74;
        }
    }

   public void setMappingList(List<Mapping> list){
        mappingList.clear();
        mappingList.addAll(list);
        setList(mappingList);
        fireTableDataChanged();
    }
  
   public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
       Mapping currentRow = mappingList.get(rowIndex);
       Object oldValue = currentRow.get(columnIndex);
       if((oldValue ==null && aValue == null) || (oldValue != null &&oldValue.equals(aValue))){
        return;
       }
       if(currentRow != null) {
           currentRow.set(columnIndex, aValue);
           updateMappingRow(currentRow);
       }
   }

     public void setList(List<Mapping> list){
        //fill data
        dataMesh = new Object[mappingList.size()][allColumns.size()];
        for (int i = 0; i < mappingList.size(); i++) {
            Mapping mapping = mappingList.get(i);
            if(null != mapping){
                dataMesh[i][NAME] = mapping.getName();
            }
            if(null != mapping.getType()){
                dataMesh[i][TYPE] = mapping.getType();
            }
           
            for(int k = 0; k < columns.length; k ++){
                String s = columns[k];
                int j = groupColumns.indexOf(s);
                if(k == 0 && mapping.getType().equalsIgnoreCase("CDR_Format_ID")){
                   String xdrid = mapping.getXdrId();
                      if (null != xdrid && !"".equals(xdrid) ) {
                            dataMesh[i][changeToTotalColumnIndex(j, 0)] = xdrid;
                      }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 0)] = "";
                      }
                      String cdr_format_id = mapping.getCdrFormatId();
                      if(null != cdr_format_id && !"".equals(cdr_format_id) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 1)] = cdr_format_id;
                      }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 1)] = "";
                      }
                      String rule_id = mapping.getRuleId();
                      if(null != rule_id && !"".equals(rule_id) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 2)] = rule_id;
                      }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 2)] = "";
                      }
                      String encode_dict_id = mapping.getEncodeDIctId();
                      if(null != encode_dict_id && !"".equals(encode_dict_id) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 3)] = encode_dict_id;
                      }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 3)] = "";
                      }
                      String output_encode_type = mapping.getOutputEncodeType();
                      if(null != output_encode_type && !"".equals(output_encode_type) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 4)] = output_encode_type;
                      }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 4)] = "";
                      }
                }else if(k == 1 && mapping.getType().equalsIgnoreCase("Distribution_Config_ID")){
                        String  distribute_config_id = mapping.getDisConID();
                        if(null != distribute_config_id && !"".equals(distribute_config_id) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 0)] = distribute_config_id;
                        }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 0)] = "";
                        }
                        String default_destination = mapping.getDeDest();
                        if(null != default_destination && !"".equals(default_destination) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 1)] = default_destination;
                        }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 1)] = "";
                        }
                        String default_directory = mapping.getDeDir();
                        if(null != default_directory && !"".equals(default_directory) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 2)] = default_directory;
                        }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 2)] = "";
                        }
                        String default_extension = mapping.getDeExt();
                        if(null != default_extension && !"".equals(default_extension) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 3)] = default_extension;
                        }else{
                            dataMesh[i][changeToTotalColumnIndex(j,3)] = "";
                        }
                        String distributiont_type = mapping.getDeType();
                        if(null != distributiont_type && !"".equals(distributiont_type) ){
                            dataMesh[i][changeToTotalColumnIndex(j, 4)] = distributiont_type;
                        }else{
                            dataMesh[i][changeToTotalColumnIndex(j, 4)] = "";
                        }
                       
                   
                }
            }
        }
     }

    @Override
    public String getColumnName(int column) {
        return allColumns.get(column);
    }

    @Override
    public int getGroupColumnCounts() {
        return groupColumns.size();
    }

    @Override
    public String getGroupColumnName(int idx) {
        return groupColumns.get(idx);
    }

    @Override
    public int getGroupColumnSubCounts(int column) {
        return groupChildSize.get(column);
    }

    @Override
    public int getSingleColumnCount() {
        return singleColumns.length;
    }


    @Override
    public int changeToTotalColumnIndex(int groupIndex, int index) {
        int k = 0;
        for (int i = 0; i < groupIndex; i++) {
            k += groupChildSize.get(i);
        }
        return singleColumns.length + k + index;
    }

    public int getColumnCount() {
        return allColumns.size();
    }

    public Mapping getMatriculateResultCom(int idx){
        return mappingList.get(idx);
    }

    public void addMappingRow(int idx,Mapping mapping){
         mappingList.add(idx,mapping);
         setList(mappingList);
         fireTableRowsInserted(idx, idx);
    }

    public void updateMappingRow(Mapping mapping){
        int idx = mappingList.indexOf(mapping);
        mappingList.set(idx, mapping);
        setList(mappingList);
        fireTableRowsUpdated(idx, idx);
    }

    public void deleteMappingRow(Mapping mapping){
        int idx = mappingList.indexOf(mapping);
        mappingList.remove(idx);
        setList(mappingList);
        fireTableRowsDeleted(idx, idx);
    }
    public void deleteMappingRows(int [] rowIndexs){
     for(int i =0 ;i < rowIndexs.length ; i++){
       mappingList.remove(rowIndexs[i]);
          setList(mappingList);
          fireTableRowsDeleted(rowIndexs[i], rowIndexs[i]);
     }
     
    }

    public List<Mapping> getList(){
        return mappingList;
    }
   
    public boolean isCellEditable(int row, int column) {
     String type  = mappingList.get(row).getType();
     String columnName = getColumnName(column);
     if(type.equalsIgnoreCase("CDR_Format_ID")){
      for(int i =0 ; i < subColumnsDis.length ; i++){
       if(columnName.equalsIgnoreCase(subColumnsDis[i])){
        return false;
       }
      }
     }else if(type.equalsIgnoreCase("Distribution_Config_ID")){
      for(int i =0 ; i < subColumnsCDR.length ; i++){
       if(columnName.equalsIgnoreCase(subColumnsCDR[i])){
        return false;
       }
      }
     }
        return true;
    }

}


 

 

class TableModel(QAbstractTableModel): def __init__(self, data=None, headers=None, parent=None): super().__init__(parent) # 初始化数据(二维列表:每行是一个列表,对应表格的一行数据) #self._data = data if data else [] self._data = [] # 列标题(列表,如["姓名", "年龄", "性别"]) #self._headers = headers if headers else [] self._headers = ["SID", "Time", "Chn", "T/Rx", "ID_index", " SendType", "RemoteFlag", "ExternFlag", "Len", "Data(hex)"] def rowCount(self, parent=QModelIndex()): #"""返回行数(必须重写)""" return len(self._data) def columnCount(self, parent=QModelIndex()): #"""返回列数(必须重写)""" # new 0722 # return len(self._headers) if self._data else 0 return len(self._headers) # new 0722 # 单元格数据 def data(self, index, role=Qt.DisplayRole): #"""返回指定位置的数据(必须重写)""" # new 0723 if role == Qt.TextAlignmentRole: return Qt.AlignCenter # new 0723 if not index.isValid() or role != Qt.DisplayRole: return None # 仅处理显示角色(DisplayRole) row = index.row() col = index.column() # new 0723 if role == Qt.DisplayRole and col == 0: value = self._data[row][col].split(" ")[0] return str(value) # new 0723 if row >= len(self._data) or col >= len(self._headers): return None return self._data[row][col] # 返回第row行第col列的数据 # 表头 def headerData(self, section, orientation, role=Qt.DisplayRole): #"""返回列标题(可选重写)""" if orientation == Qt.Horizontal and role == Qt.DisplayRole: return self._headers[section] if section < len(self._headers) else None # new 添加行号行头 0721 if orientation == Qt.Vertical and role == Qt.DisplayRole: return str(section + 1) # new 添加行号行头 0721 return None # 垂直标题(行号)默认使用行索引,无需额外处理 # new 0725 可编辑窗口 # def setData(self, index, value, role=Qt.EditRole): # if role == Qt.EditRole and index.isValid(): # row = index.row() # col = index.column() # if row < len(self._data) and col < len(self._data[0]): # self._data[row][col] = value # self.dataChanged.emit(index, index) # 通知视图数据已更改 # return True # return False # def flags(self, index): # return super().flags(index) | Qt.ItemIsEditable # new 0725 可编辑窗口 def add_row(self, row_data): #"""动态添加一行数据(触发视图更新)""" # 通知视图:开始插入行(参数:父索引、插入位置起始行、结束行) self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) self._data.append(row_data) # 实际添加数据到模型 self.endInsertRows() # 通知视图:插入完成 怎么获取当前按钮所在行数
08-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值