JTable更改行类

时间:2017-06-14 07:50:37

标签: java swing jtable

正如标题所暗示的,我正在试图弄清楚如何更改行的类,但更具体地说,我正在尝试更改某些行的类,而不是每行。我能找到的就是如何改变列的类别。

我似乎无法找到如何在特定行上调整类。如果有人能指出我正确的方向,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

这就是我接近它的方式:

public class TableRenderer {
    interface ComponentTextSetter<T> {
        void setText(String value, T component);
    }
    private static final Map<Component, ComponentTextSetter> components = new HashMap() {
        {
            put(new JLabel(), (ComponentTextSetter<JLabel>) (value, component) -> component.setText(value));
            put(new JTextField(),
                    (ComponentTextSetter<JTextField>) (value, component) -> component.setText(value));
            put(new JComboBox<>(), (ComponentTextSetter<JComboBox>) (value, component) -> {
                component.addItem(value);
                component.setSelectedItem(value);
            });
        }
    };

    private static TableCellRenderer renderer = new DefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            Component jComponent = new ArrayList<>(components.keySet()).get(row % components.size());
            components.get(jComponent).setText(value.toString(), jComponent);
            return jComponent;
        }
    };

    public static void main(String[] args) {
        TableModel tableModel = new DefaultTableModel(10, 3) {
            @Override
            public Object getValueAt(int arg0, int arg1) {
                return "value" + new Random().nextInt(4);
            }
        };
        JTable jTable = new JTable(tableModel);
        jTable.setDefaultRenderer(Object.class, renderer);
        JOptionPane.showMessageDialog(null, jTable);
    }
}