Is there any method like getColumnClass in JTable to set row specific data types?

夙愿已清 提交于 2019-12-23 05:11:46

问题


I have a JTable with two columns: a key name and the value. In the value columns are multiple data types allowed like this image:

So in column 1 I might have a boolean in row 1 and a string in row 2. But the method getColumnClass(...) only allows me to set a data type for the complete column.

Is there any way to set column-row specific data types?

Greetings, mythbu


回答1:


You cannot have two data types to the same column. But for your case, my suggestion is use rendering.

  1. Read about Editors and Renderers.

  2. Define the column data type as a component class which contains a JPanel.

  3. Render the column. Your Renderer class returns a Panel to the column. It should have a constraint, basing on that you should add components to the Panel and return the Panel.

This example shows how rendering can be used in these kind of cases.

class PanelCellRenderer extends JPanel implements TableCellRenderer {
public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
       // row number is used as a constraint.
        if(row == 0) {
            this.add( new JTextField("", 20));
        } else if(row == 1) {
            this.add( new JCheckBox());
        } else if(row == 2) {
            this.add( new JButton());
        } else {
            this.add( new JLabel("Row-4"));
        }
        return this;
   }
}

// Output:

The first row is a panel with JTextField. Similarly 2nd, 3rd rows has JCheckBox and JButton. 4th row has a JLabel with text.

P.S: This is just a try. Even I haven't done this before. Please correct me if I am wrong.



来源:https://stackoverflow.com/questions/13550862/is-there-any-method-like-getcolumnclass-in-jtable-to-set-row-specific-data-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!