[英]JTable ImageIcon and String
I want to create a JTable
where in the cells there could be an ImageIcon
, String
or both. 我想创建一个
JTable
,其中的单元格中可以有ImageIcon
, String
或两者都有。 I've already tried solutions like table.setvalue()
or just adding the Icon
to the Object Array
for creating the JTable
. 我已经尝试过诸如
table.setvalue()
类的解决方案,或者只是将Icon
添加到Object Array
以创建JTable
。
for (int n = 0; n < tableHeight; n++) {
for (int m = 0; m < tableWidth; m++) {
if ((n + m) == labelArray.size()) {
break;
}
if (labelArray.get(n + m).iconMode) { //iconMode is True if there is an icon instead of line text
data[n][m] = null;
} else {
String text = new String("<html><p>" + labelArray.get(n + m).lineOne + "<br>" + labelArray.get(n + m).lineTwo + "<p></html>");
data[n][m] = text;
}
}
}
table = new JTable(data, columnNames);
renderer = new DefaultTableCellRenderer();
renderer.setHorizontalTextPosition(JLabel.CENTER);
renderer.setHorizontalAlignment(JLabel.CENTER);
for (int n = 0; n < tableWidth; n++) {
table.getColumnModel().getColumn(n).setCellRenderer(renderer);
table.getColumnModel().getColumn(n).setWidth(50);
}
there could be an ImageIcon, String or both.
可能有ImageIcon,String或两者都有。
You will need to create a custom object to store in the TableModel. 您将需要创建一个自定义对象以存储在TableModel中。 This object will contain two properties:
该对象将包含两个属性:
Then you will need to create a custom renderer (not use the default renderer) to display this object. 然后,您将需要创建一个自定义渲染器(不使用默认渲染器)以显示该对象。
The custom renderer might look something like: 自定义渲染器可能类似于:
class CustomRenderer extends DefaultTableCellRenderer
{
public CustomRenderer()
{
super();
setHorizontalTextPosition(JLabel.CENTER);
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
CustomObject custom = (CustomObject)value;
setText( custom.getText() );
setIcon( custom.getIcon() );
return this;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.