Java JTable setting Column Width

后端 未结 9 1573
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 09:57

I have a JTable in which I set the column size as follows:

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredW         


        
9条回答
  •  既然无缘
    2020-12-02 11:03

    Reading the remark of Kleopatra (her 2nd time she suggested to have a look at javax.swing.JXTable, and now I Am sorry I didn't have a look the first time :) ) I suggest you follow the link

    I had this solution for the same problem: (but I suggest you follow the link above) On resize the table, scale the table column widths to the current table total width. to do this I use a global array of ints for the (relative) column widths):

    private int[] columnWidths=null;
    

    I use this function to set the table column widths:

    public void setColumnWidths(int[] widths){
        int nrCols=table.getModel().getColumnCount();
        if(nrCols==0||widths==null){
            return;
        }
        this.columnWidths=widths.clone();
    
        //current width of the table:
        int totalWidth=table.getWidth();
    
        int totalWidthRequested=0;
        int nrRequestedWidths=columnWidths.length;
        int defaultWidth=(int)Math.floor((double)totalWidth/(double)nrCols);
    
        for(int col=0;colcol){
                width=columnWidths[col];
            }
            totalWidthRequested+=width;
        }
        //Note: for the not defined columns: use the defaultWidth
        if(nrRequestedWidthscol){
                //scale the requested width to the current table width
                width=(int)Math.floor(factor*(double)columnWidths[col]);
            }
            table.getColumnModel().getColumn(col).setPreferredWidth(width);
            table.getColumnModel().getColumn(col).setWidth(width);
        }
    
    }
    

    When setting the data I call:

        setColumnWidths(this.columnWidths);
    

    and on changing I call the ComponentListener set to the parent of the table (in my case the JScrollPane that is the container of my table):

    public void componentResized(ComponentEvent componentEvent) {
        this.setColumnWidths(this.columnWidths);
    }
    

    note that the JTable table is also global:

    private JTable table;
    

    And here I set the listener:

        scrollPane=new JScrollPane(table);
        scrollPane.addComponentListener(this);
    

提交回复
热议问题