I am trying to add a jpanel as a row to my jtable, something that looks like this: table , the red buttons are supposed to be invisible till the edit button on the top right is clicked.
I tried something like this:
JPanel row = new JPanel();
row.setBackground(new Color(255, 255, 255, 0));
row.setAutoscrolls(true);
row.setBorder(new EmptyBorder(0, 0, 0, 0));
row.setLayout(new TableLayout(new double[][]{
{TableLayout.FILL, TableLayout.FILL},
{TableLayout.PREFERRED}}));
((TableLayout)row.getLayout()).setHGap(0);
((TableLayout)row.getLayout()).setVGap(0);
JLabel deleteRow = new JLabel();
deleteRow.setText("");
deleteRow.setIcon(new ImageIcon(getClass().getResource("/com/example/clinicsystem/pictures/remove.png")));
JLabel rowText = new JLabel();
rowText.setText(comboBoxPermissions.getSelectedItem().toString());
rowText.setForeground(Color.black);
rowText.setFont(new Font("Helvetica-Normal", Font.PLAIN, 14));
rowText.setHorizontalAlignment(SwingConstants.CENTER);
row.add(deleteRow, new TableLayoutConstraints(0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
row.add(rowText, new TableLayoutConstraints(0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
model.addRow(new JPanel[]{row});
but when I run the project, I get this text inside the row where this panel is supposed to be:
javax.swing.JPanel[,0,0,0x0,invalid,layout=info.clearthought.layout.TableLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.border.EmptyBorder@254d8187,flags=33554441,maximumSize=,minimumSize=,preferredSize=]
I get this text inside the row where this panel is supposed to be:
By default render of the table will simply invoke the toString()
method on the data in the TableModel
, so you see the toString() value of the JPanel.
A JTable
is not designed to add a component to the TableModel. It is designed for you to add data to the TableModel. The data is then rendered based on the type of data added to the model.
the red buttons are supposed to be invisible till the edit button on the top right is clicked.
So you would need to add a column of data to represent the red buttons. Start by reading Table Button Column. It demonstrates how to add a column of buttons to the table and how to add an Action to be invoked when you click on the button.
If you don't want the column to be visible then you can remove the TableColumn
from the TableColumnModel
, after you create the table. Then when the "edit" button is clicked, you can add the TableColumn
back to the TableColumnModel
.
The TableColumnModel
has methods like removeTableColumn(...)
and addTableColumn(..)
to help with this. You can also use the getColumn(...)
method of the JTable to get the column to remove and save for future use.
Read the section from the Swing tuturial on How to Use Table for more information about renderers and editors.