简体   繁体   中英

How do I add a JLabel[] to a JTable?

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;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM