1

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?

Mike
  • 99
  • 2
  • 3
  • 13
  • 1
    `JLabels` are just component text representations. Can you not just add the text of the labels? – Reimeus Apr 12 '13 at 14:35
  • @Reimeus, i would, but I want the background to be coloured. Is there a way of changing the background colour of the JTable cells? – Mike Apr 12 '13 at 14:36
  • 6
    I'd say to forget adding the `JLabels`, add the text and use a `TableCellRenderer`. Have a look at _[Editors & Renderers](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender)_ – Reimeus Apr 12 '13 at 14:40

2 Answers2

2

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

Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

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;
}
}
Raghunandan
  • 132,755
  • 26
  • 225
  • 256