Search code examples
javaswingjtablejbuttonflowlayout

Unable to add JButtons wrapped in JPanel into JTable


I am having a JTable, where the final column of the table is for adding 2 buttons. Below is the format of my JTable.

enter image description here

Below is my code

private class ViewLawyersDisplayData extends ComponentAdapter
     {
        @Override
        public void componentShown(ComponentEvent e) 
        {
            dbConnector = new DBHandler();
            dbConnector.makeConnection();

            ResultSet rs =  dbConnector.selectAllLawyerDetails();

            if(rs==null)
            {
                JOptionPane.showMessageDialog(null,"The table is empty");
            }
            else
            {
                try
                {
                    while(rs.next())
                    {
                        int id = rs.getInt("lawyer_id");
                        String name = rs.getString("Name");
                        String address = rs.getString("Address");
                        String email = rs.getString("Email");
                        String phone = rs.getString("Phone");

                        JButton update = new JButton("Update");
                        JButton delete = new JButton("Delete");

                        JPanel btnPanel = new JPanel();
                        btnPanel.setLayout(new FlowLayout());
                        btnPanel.add(update);
                        btnPanel.add(delete);

                        Object[]row = {id,name,address,email,phone,btnPanel};

                        DefaultTableModel model = (DefaultTableModel) viewLawyersTable.getModel();
                        model.addRow(row);
                    }
                }
                catch(SQLException sqlE)
                {
                    JOptionPane.showMessageDialog(null,sqlE.getLocalizedMessage());
                }
            }
        }
     }

However I am unable to add the buttons into the final columns. Instead of showing the buttons, it shows some error text in the column. Below is the error text it shows to me.

javax.swing.JPanel[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]

How can I fix this issue?


Solution

  • You can't add Swing components to a table because a table is not used to display actual components.

    See Table Button Column for one solution that provides the renderer/editor for a button in a column of the table.