Question

Here is my piece of code -

class ButtonCellRenderer extends AbstractCellEditor
    implements TableCellRenderer,TableCellEditor,MouseListener{

        JTable table;
        JLabel rendererLabel ;
        JButton editButton ;
         String text = "BAKRA";


        public ButtonCellRenderer(JTable table, int column) {
            this.table = table;
        rendererLabel = new JLabel("value.png");


            //rendererBut.setToolTipText("BUNTHAAAAAAAAAAAAAA");
            rendererLabel .addMouseListener(this);


             TableColumnModel columnModel = table.getColumnModel();
             columnModel.getColumn(column).setCellRenderer( this );
                columnModel.getColumn(column).setCellEditor( this );
        }

        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row
                , int column) {
            // TODO Auto-generated method stub
            rendererLabel.setOpaque(true);

    if(isSelected)
    rendererLabel.setBackground( table.getSelectionBackground());
    else
    rendererLabel.setBackground(Color.WHITE);


            return rendererLabel ;
        }

        public Component getTableCellEditorComponent(
                JTable table, Object value, boolean isSelected, int row, int column)
        {

            return rendererLabel ;
        }

        public Object getCellEditorValue() {
            // TODO Auto-generated method stub
            return text;
        }

        public void mousePerformed(ActionEvent ev) {
            // TODO Auto-generated method stub




            JOptionPane.showMessageDialog(null, "UOBS BUTTON PRESSED",
                    "BUTTON PRESSED"
                    ,JOptionPane.ERROR_MESSAGE);
        }



    }

In this everything is working fine but - Actually when the JTable window opens and if I click directly on the JLabel (image) based Column , then the image is gone for a while and the table returns the selected row as -1. One more point is that the Row selection as well restricted to the previous column.

Precisely , If my Table has 4 column and Image(JLabel) is on the column number 4th, then if I directly click on the image or column 4th , then the row selection happens till the 3rd column and it returns the row selection as -1. But If I select any other column, the everything is proper and works fine.

Was it helpful?

Solution

There is no need to create a custom renderer to display an image. JTable already supports a default renderer for Icons. Just add an ImageIcon to the model. Then you need to override the getColumnClass() method to return Icon.class for that column and the proper renderer will be used.

If you are trying to create some kind of clickable button then you can use the Table Button Column which also supports icons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top