[英]How do I add a JLabel[] to a JTable?
I have an array of JLabels which I want to add to a JTable. 我有一个要添加到JTable的JLabel数组。 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
. 使用add方法不是将组件添加到
JTable
。 Components should never be added directly to a JTable
or its TableModel
. 绝对不应将组件直接添加到
JTable
或其TableModel
。
JLabels
are just Swing components that render text. JLabels
只是显示文本的Swing组件。
You can use a TableCellRenderer
. 您可以使用
TableCellRenderer
。 Have a look at Editors & Renderers 看看编辑器和渲染器
You cannot just add myJTable.add(myJLabelArray). 您不能只添加myJTable.add(myJLabelArray)。 As Reimeus pointed out use Renderers
正如Reimeus指出的那样,使用渲染器
jTable1.getColumnModel().getColumn(0).setCellRenderer(new Renderer()); //set column1 with jlabel
Your render should extend DefaulttableCellRenderer 您的渲染应扩展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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.