How to center in JTable cell a value?

前端 未结 6 769
迷失自我
迷失自我 2020-12-08 14:24

How to center a value in JTable cell? I\'m using Netbeans.

6条回答
  •  余生分开走
    2020-12-08 15:08

    I had a similar problem. I wanted to align a single cell depending on the value of another cell. If cell X was NULL, then cell Y should be RIGHT aligned. Else, cell Y should be LEFT aligned.

    I found this solution really helpful. It consists on creating a custom Render, extending DefaultTableCellRender.

    Here's the code:

    public class MyRender extends DefaultTableCellRenderer{
    
    @Override
     public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column){
        super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
        MyTableModel mtm = (MyTableModel)table.getModel();
        switch(column){
            case Y : 
                if(mla.getValueAt(row,X)!=null)
                    setHorizontalAlignment(SwingConstants.RIGHT);
                else
                    setHorizontalAlignment(SwingConstants.LEFT);
                break;
         }
        return this;
       }
    
     }
    

    After that, just create a new instance of MyRender and set it to column Y, in this case. I do this when I load the information on the table.

    MyRender render = new MyRender();
    table.getColumnModel().getColumn(Y).setCellRender(render);
    

    Hope it's useful!

提交回复
热议问题