简体   繁体   中英

Java - JTable Custom TableCellRenderer + Reordering Allowed

My code is pretty long so i am making a short example of my issue.

I have a JTable with 2 columns , both containing numbers. I need one column, let's say column B to render differently. That's why i created a customer TableCellRenderer which is converting the number to a JPanel (several icons, text etc.). I am setting the class of column B to JPanel and of column A to Number when creating the JTable:

    table = new JTable(model)
    {
        public Class getColumnClass(int column)
        {
            if(column == 1)
            {
                return Number.class;
            }

            if(column == 2)
            {
                return JPanel.class;
            }

            return super.getColumnClass(column);

        }
    }

    table.setDefaultRenderer(JPanel.class, (TableCellRenderer) new RendererCurrency());

    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment(JLabel.CENTER);

    table.setDefaultRenderer(Number.class , centerRenderer);

Everything is working fine so far, both columns display the correct value and get rendered correct. The problem starts when i want to have Reordering Allowed = true.

As soon as you switch the columns in the running software the columns and its values will be switched...

but not the renderer

This causes column A to be rendered and column B to be standard, where it should be vice versa.

This is probably because i set the class for a specific column index but i don't know how else i should do this.

Thanks to @Manu i was able to fix this problem by converting the column index to the view:

        public Class getColumnClass(int column)
        {
            if(column == table.convertColumnIndexToView(1))
            {
                return Number.class;
            }

            if(column == table.convertColumnIndexToView(2))
            {
                return JPanel.class;
            }

            return super.getColumnClass(column);

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM