I have an array of JLabels which I want to add to a JTable. I tried using
myJTable.add(myJLabelArray);
Hoping it would work, but it doesn't (Obviously, otherwise I wouldn't be here).
Can somebody please help?
I have an array of JLabels which I want to add to a JTable. I tried using
myJTable.add(myJLabelArray);
Hoping it would work, but it doesn't (Obviously, otherwise I wouldn't be here).
Can somebody please help?
Using add method is not the way to add components to a JTable
. Components should never be added directly to a JTable
or its TableModel
.
JLabels
are just Swing components that render text.
You can use a TableCellRenderer
. Have a look at Editors & Renderers
You cannot just add myJTable.add(myJLabelArray). As Reimeus pointed out use Renderers
jTable1.getColumnModel().getColumn(0).setCellRenderer(new Renderer()); //set column1 with jlabel
Your render should extend DefaulttableCellRenderer
class Renderer extends DefaultTableCellRenderer {
JLabel lbl = new JLabel();
//ImageIcon icon = new ImageIcon(getClass().getResource("sample.png"));
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
lbl.setText("hello");
//lbl.setIcon(icon);
return lbl;
}
}