我试图通过覆盖此类JLabel
方法在JTable
内显示getColumnClass
JLabel myLabel = new JLabel("ok");
String[] columnNames = {"","",""};
Object[][] data =
{
{myLabel, myLabel, myLabel},
{myLabel, myLabel, myLabel},
{myLabel, myLabel, myLabel},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable( model )
{
public Class getColumnClass(int column)
{
return JLabel.class;
}
};
但它会显示类似这样的东西(哈希码?)
javax.swing.JLabel[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=ok,verticalAlignment=CENTER,verticalTextPosition=CENTER]
问题是什么?如何解决这个问题?
修改
如果使用相同的逻辑来显示ImageIcon
ImageIcon myLabel = new ImageIcon(path); // ignore the variable name
并更改为getColumnClass
public Class getColumnClass(int column)
{
return ImageIcon.class;
}
答案 0 :(得分:5)
JComponent
到JTable
或其Model
,应存储only value used for Renderer,
- Boolean — rendered with a check box.
- Number — rendered by a right-aligned label.
- Double, Float — same as Number, but the object-to-text translation is performed
by a NumberFormat instance (using the default number format for the current locale).
- Date — rendered by a label, with the object-to-text translation performed
by a DateFormat instance (using a short style for the date and time).
- ImageIcon, Icon — rendered by a centered label.
- Object — rendered by a label that displays the object's string value.
Renderer
默认返回JLabel
/ JComponent
阅读Oracle教程How to use Tables了解工作代码示例