在JTable中显示JLabel

时间:2013-11-22 07:44:32

标签: java swing jtable jlabel

我试图通过覆盖此类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;
            }

1 个答案:

答案 0 :(得分:5)

- 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了解工作代码示例