user3239711
user3239711

Reputation: 649

Cell renderer and the lost focus

I am using a JTable and in order to change the format of numbers. I have extended the DefaultTableRenderer class.

In the method getTableCellRenderedComponent, I retrun a new JLabel with the proper format. My problem is by doing this the rectangle (border) that underlines the cell which has the focus has disappeared.

Is there a way to get the default border displayed whenever a cell has the focus with my custom render?

Upvotes: 0

Views: 437

Answers (2)

camickr
camickr

Reputation: 324118

in order to change the format of numbers. I have extended the DefaultTableRenderer class.

Check out Table Format Renderers for an easier way to customize the renderer when all you need to do is format the data. That is you should override the setValue(...) method instead of the getTableCellRenderer(...) method.

Upvotes: 2

alex2410
alex2410

Reputation: 10994

If you use DefaultTableRenderer you can call super() method and get Border from returned component. Try next example:

import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class TestFrame extends JFrame {

    public TestFrame() {
        init();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void init() {
        JTable t = new JTable(3,3);
        t.getColumnModel().getColumn(0).setCellRenderer(getRenderer());
        add(new JScrollPane(t));
    }

    private TableCellRenderer getRenderer() {
        return new DefaultTableCellRenderer(){

            private JLabel l = new JLabel();
            {
                l.setOpaque(true);
            }

            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus,
                    int row, int column) {
                JComponent tableCellRendererComponent = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus,row, column);
                l.setText(value == null ? "" : value.toString());
                l.setBorder(tableCellRendererComponent.getBorder());
                l.setBackground(tableCellRendererComponent.getBackground());
                l.setForeground(tableCellRendererComponent.getForeground());
                return l;
            }
        };
    }

    public static void main(String... s){
        new TestFrame();
    }

}

Upvotes: 1

Related Questions