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

有些话、适合烂在心里 提交于 2019-12-11 13:45:15

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/15974108/how-do-i-add-a-jlabel-to-a-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!