How to insert a button in a jtable cell

35 views Asked by At

I tried this code but my button is just visible but not clickable and in addition how do I add an icon, when I choose an image as an icon the button is resized to the size of that image which doesn't look nice Here is my code: ''' dataview.getColumnModel().getColumn(4).setCellRenderer(new ButtonRenderer());

//SET OUR CUSTOM EDITOR TO OUR COLUMN

dataview.getColumnModel().getColumn(4).setCellEditor(new ButtonEditor(new JTextField()));

class ButtonRenderer extends JButton implements TableCellRenderer {

    public ButtonRenderer() {
        setOpaque(true);
    }

    @Override
    public Component getTableCellRendererComponent(JTable dataview, Object obj, boolean selected, boolean focused, int row, int col) {
       
        setText((obj==null) ? "" : obj.toString());
        return this;
    }
}

class ButtonEditor extends DefaultCellEditor{
    
    protected JButton btn;
    protected String lbl;
    protected Boolean clicked; 
    
    public ButtonEditor(JTextField txt) {
        super(txt);
        
        btn = new JButton();
        btn.setOpaque(true);
        
        
        //WHEN BUTTON IS CLICKED.
        btn.addActionListener((ActionEvent e) -> {
            fireEditingStopped();
        });
    
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable dataview, Object obj, boolean selected, int row, int col) {
        
        //SET BUTTON TEXT, SET CLICKED TO TRUE, THEN RETURN THE BIN OBJECT
        lbl = (obj==null)?"":obj.toString();
        btn.setText(lbl);
        clicked = true;
        
        return btn;
    }

    @Override
    public Object getCellEditorValue() {
        
        if(clicked){
            JOptionPane.showMessageDialog(btn, lbl+" Clicked");
            
        }
        clicked=false;
        return lbl;
        
    }

    @Override
    public boolean stopCellEditing() {
        //SET CLICKED TO FALSE
        clicked = false;
        return super.stopCellEditing();
    }
    @Override
    protected void fireEditingStopped(){
        super.fireEditingStopped();
    }
}

}'''

0

There are 0 answers