我试图通过覆盖这样的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;
            }

最佳答案

don't put JComponentJTable或其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,获取有效的代码示例

09-26 22:10
查看更多