2

我正在处理一个相当复杂的 JTable。行数和列数是根据列表构建的。然后取决于单元格编辑器需要更改哪一行的哪一列。在寻找解决方案时,我发现了这个: http ://www.java2s.com/Code/Java/Swing-Components/EachRowwithdifferentEditorExample.htm

我按原样获取该代码并运行它只是为了确保它在当前的 Java 版本中运行并且确实如此。所以我将它应用到我已经构建的 JTable 中,但似乎正在发生的事情是,当我将它应用到多个列时,它最终只适用于第一列。

我整理了一段完全可执行的代码,我已经评论并设置了它来模拟我的数据库数据。该代码的注释相当不错,因此应该很容易理解。这个样本至少对我来说仍然会产生问题。

如果你们中的任何人都可以看到有什么问题,我将非常感谢您的帮助。

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;


public class EachRowEditorExample extends JFrame {

    public EachRowEditorExample() {
        super("EachRow Editor Example");
        List<Membership> _Memberships = new ArrayList<Membership>();
        DefaultTableModel DataModel;

        //Lets Start by simluating the data.
        for (int z = -2; z < 10; z++)
        {
            Membership m = new Membership();
            m.setId(z);
            if (z == -2) 
            {
                m.setMembership("Employee");
                m.setEft(false);
            }
            else if (z == -1) 
            {
                m.setMembership("NONE");
                m.setEft(false);
            }
            else
            {
                m.setMembership("Membership " + z);
                if (z < 3 )
                    m.setEft(true);
                else
                    m.setEft(false);
            }
            _Memberships.add(m);
        }

        //*******************************************************
        // Starts Copy and paste from Program
        //*******************************************************
        //lets build our Data Model
        int size = _Memberships.size(); 
        Object[][] rows = new Object[size][];
        String[] cols = new String[size];
        int x = 0;
        for(Iterator<Membership> i = _Memberships.iterator(); i.hasNext(); )
        {
            Membership side = i.next();
            cols[x] = side.getMembership();
            Object[] row = new Object[size];
            int b = 0;
            for(Iterator<Membership> j = _Memberships.iterator(); j.hasNext(); )
            {
                Membership top = j.next();
                if (side.getId() == top.getId() && (side.isEft() && top.isEft()))
                {
                    row[b] = null;
                }
                else
                    row[b] = NUHPADX(side.getId(), top.getId());
                b++;
            }
            rows[x] = row;
            x++;
        }
        DataModel = new DefaultTableModel(rows,cols);


        //Now Lets create our JTable and configure it.
        JTable table = new JTable(DataModel) {
            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                Object t = getValueAt(rowIndex, rowIndex);
                if (t == null)
                    return false;
                else
                    return true;
            }

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
            {
                Component c = super.prepareRenderer(renderer, row, column);

                Object t = getValueAt(row, column);
                if (t == null)
                {
                    c.setBackground(Color.black);
                }
                else
                {
                    Color PRIMARY_ROW_COLOR = Color.white; 
                    Color ALTERNATE_ROW_COLOR = new Color(0xA9F1ED);

                    //even index, selected or not selected
                    if (row % 2 == 0) 
                    {
                        if (column % 2 == 0) 
                            c.setBackground(PRIMARY_ROW_COLOR.darker());
                        else
                            c.setBackground(PRIMARY_ROW_COLOR);
                    }
                    else 
                    {
                        if (column % 2 == 0) 
                            c.setBackground(ALTERNATE_ROW_COLOR.darker());
                        else
                            c.setBackground(ALTERNATE_ROW_COLOR);
                    }
                }
                return c;
            }

        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.getTableHeader().setReorderingAllowed(false);
        JList rowHeader = new JList(cols);
        rowHeader.setCellRenderer(new RowHeaderRenderer(table));

        //Lets Place the new table in a Scroll Pane Since there could be alot of data.
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setRowHeaderView(rowHeader);
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        //Now lets Build the Cell Editors
        int c = 0;
        int r = 0;
        for(Iterator<Membership> a = _Memberships.iterator(); a.hasNext();)
        {
            Membership top = a.next();
            EachRowEditor rowEditor = new EachRowEditor(table);
            for(Iterator<Membership> b = _Memberships.iterator(); b.hasNext();)
            {
                Membership side = b.next();

                if (side.getId() == top.getId() && (side.isEft() && top.isEft()))
                {
                    //rowEditor.setEditorAt(r, null);
                }
                else if (side.getId() != top.getId() && (side.isEft() && top.isEft()))
                {
                    NuhpadxCell t = new NuhpadxCell(side, top, new DefaultComboBoxModel(new String[] {"N", "U", "D", "A"}));
                    t.setSelectedItem(NUHPADX(side.getId(), top.getId()));
                    rowEditor.setEditorAt(r, new DefaultCellEditor(t));
                }
                else 
                {
                    NuhpadxCell t = new NuhpadxCell(side, top, new DefaultComboBoxModel(new String[] {"N", "A", "H", "X", "P"}));
                    t.setSelectedItem(NUHPADX(side.getId(), top.getId()));
                    rowEditor.setEditorAt(r, new DefaultCellEditor(t));
                }
                r++;
            }
            table.getColumn(top.getMembership()).setCellEditor(rowEditor);
            table.revalidate();
            c++;
        }

        table.removeColumn(table.getColumn("NONE"));

        //*******************************************************
        // Ends Copy and paste from Program
        //*******************************************************
        setSize(1060, 600);
        setVisible(true);
    }

    //This function jsut simluates a entire class
    public String NUHPADX(int side, int top)
    {
        Random generator = new Random();
        int roll = generator.nextInt(7);
        switch (roll)
        {
            case 0:
                return "N";
            case 1:
                return "U";
            case 2:
                return "H";
            case 3:
                return "P";
            case 4:
                return "A";
            case 5:
                return "P";
            case 6:
                return "A";
            default:
                return "N";
        }

    }

    public static void main(String[] args) {
        EachRowEditorExample frame = new EachRowEditorExample();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

//Example from http://www.crionics.com/products/opensource/faq/swing_ex/SwingExamples.html
/* (swing1.1.1) */
class EachRowEditor implements TableCellEditor {
    protected Hashtable editors;

    protected TableCellEditor editor, defaultEditor;

    JTable table;

    /**
     * Constructs a EachRowEditor. create default editor
     * 
     * @see TableCellEditor
     * @see DefaultCellEditor
     */
    public EachRowEditor(JTable table) {
        this.table = table;
        editors = new Hashtable();
        defaultEditor = new DefaultCellEditor(new JTextField());
    }

    /**
     * @param row
     *            table row
     * @param editor
     *            table cell editor
     */
    public void setEditorAt(int row, TableCellEditor editor) {
        editors.put(new Integer(row), editor);
    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        editor = (TableCellEditor) editors.get(new Integer(row));
        if (editor == null) {
            editor = defaultEditor;
        }
        return editor.getTableCellEditorComponent(table, value, isSelected, row, column);
    }

    public Object getCellEditorValue() {
        return editor.getCellEditorValue();
    }

    public boolean stopCellEditing() {
        return editor.stopCellEditing();
    }

    public void cancelCellEditing() {
        editor.cancelCellEditing();
    }

    public boolean isCellEditable(EventObject anEvent) {
        selectEditor((MouseEvent) anEvent);
        return editor.isCellEditable(anEvent);
    }

    public void addCellEditorListener(CellEditorListener l) {
        editor.addCellEditorListener(l);
    }

    public void removeCellEditorListener(CellEditorListener l) {
        editor.removeCellEditorListener(l);
    }

    public boolean shouldSelectCell(EventObject anEvent) {
        selectEditor((MouseEvent) anEvent);
        return editor.shouldSelectCell(anEvent);
    }

    protected void selectEditor(MouseEvent e) {
        int row;
        if (e == null) {
            row = table.getSelectionModel().getAnchorSelectionIndex();
        } else {
            row = table.rowAtPoint(e.getPoint());
        }
        editor = (TableCellEditor)editors.get(new Integer(row));
        if (editor == null) {
            editor = defaultEditor;
        }
    }
}

//*******************************************************
// Starts Copy and paste from Program
//*******************************************************
class RowHeaderRenderer extends JLabel implements ListCellRenderer {
    private static final long serialVersionUID = 4619707414623897299L;

    public RowHeaderRenderer(JTable table) {
        JTableHeader header = table.getTableHeader();
        setOpaque(true);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(CENTER);
        setForeground(header.getForeground());
        setBackground(header.getBackground());
        setFont(header.getFont());
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        setText((value == null) ? "" : value.toString());
        return this;
    }
}

class NuhpadxCell extends JComboBox {
    private static final long serialVersionUID = -4464709511574911230L;

    private Membership _side;
    private Membership _top;

    public NuhpadxCell(Membership s, Membership t, DefaultComboBoxModel aModel)
    {
        _side = s;
        _top = t;
        addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                DoUpdate();
            }

        });

        setModel(aModel);
    }

    private void DoUpdate() {
        // I would then update my database useing the ID of the side and top memberships as keys.
    }
}

//*******************************************************
// Ends Copy and paste from Program
//*******************************************************

//A bare Skeleton of the membership class needed to run this code.
class Membership {

    protected int id;
    protected String membership;
    protected boolean eft;

    public int getId() {
        return id;
    }
    public void setId(int value) {
        this.id = value;
    }

    public String getMembership() {
        return membership;
    }
    public void setMembership(String value) {
        this.membership = value;
    }

    public boolean isEft() {
        return eft;
    }
    public void setEft(boolean value) {
        this.eft = value;
    }
}
4

2 回答 2

2

1.问题来自代码行,

table.removeColumn(table.getColumn("NONE"));

2.然后JTables view返回不同column index的存储到,你也TableModel必须调用table.convertColumnIndexToModel()prepareRendererEditor

3.remove isCellXxxfrom JTableto Modelei

DataModel = new DefaultTableModel(rows, cols) {

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        Object t = getValueAt(rowIndex, rowIndex);
        if (t == null) {
            return false;
        } else {
            return true;
        }
    }
};

4.calltable.setPreferredScrollableViewportSize(table.getPreferredSize());然后您可以更改setSize(1060, 600);pack();

5.也加在setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);那里

6.不要扩展JFrame,创建一个局部变量

7.那么你的主要课程应该包括InitialThread

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            EachRowEditorExample frame = new EachRowEditorExample();
        }
    });
}

编辑

1,我只是想隐藏该列而不是从模型中完全删除它,这是该代码应该做的(根据 Java Docs)。

table.removeColumn(table.getColumn("NONE"));Column仅从andJTables View中的 more 中去除混凝土APIJTables tutorial,这Column仍然存在于 the 中XxxTableModel,最好在您这边测试一下

至于2,不知道为什么真的适用。

这已经得到解答,更多内容在JTable 教程中进行了描述(也请阅读下一节)

于 2012-06-25T12:49:07.753 回答
2

对于看起来很简单的事情,您的解决方案似乎非常复杂。您实际上只有两个不同的 CellEditor,它们都基于 JComboBox。

因此,更简单的解决方案是扩展DefaultCellEditorJComboBox覆盖 getTableCellEditorComponent(),具体取决于您所在的行,JComboBox使用适当的模型更新 ,然后将调用返回到super.

最终,您在表格的所有列上设置了此单元格编辑器。

还要考虑遵循 Java 编码约定(变量和方法以小写字母开头,类以大写字母开头,等等...)

编辑:

    class MyTableCellEditor extends DefaultCellEditor {
        private DefaultCellEditor defaultEditor;
        private DefaultComboBoxModel nudaModel = new DefaultComboBoxModel(new String[] { "N", "U", "D", "A" });
        private DefaultComboBoxModel nahxpModel = new DefaultComboBoxModel(new String[] { "N", "A", "H", "X", "P" });

        public MyTableCellEditor() {
            super(new JComboBox());
            defaultEditor = new DefaultCellEditor(new JTextField());
        }

        private JComboBox getComboBox() {
            return (JComboBox) editorComponent;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            Membership top = _Memberships.get(column);
            Membership side = _Memberships.get(row);

            if (side.getId() == top.getId() && side.isEft() && top.isEft()) {
                return defaultEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
            } else if (side.getId() != top.getId() && side.isEft() && top.isEft()) {
                getComboBox().setModel(nudaModel);
            } else {
                getComboBox().setModel(nahxpModel);
            }
            return super.getTableCellEditorComponent(table, NUHPADX(side.getId(), top.getId()), isSelected, row, column);
        }
    }

这是您的 TableModel 的实现:

    class MyDataModel extends AbstractTableModel{

        @Override
        public int getRowCount() {
            return _Memberships.size();
        }

        @Override
        public int getColumnCount() {
            return _Memberships.size();
        }

        @Override
        public String getColumnName(int column) {
            // Here feel free to return the appropriate column names.
            return super.getColumnName(column);
        }

        @Override
        public Object getValueAt(int row, int column) {
            return NUHPADX(_Memberships.get(row).getId(), _Memberships.get(column).getId());
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            // Here you can do whatever you want to say that is editable or not
            // If it is editable, you need to override setValueAt
            return true;
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            // Here you need to implement the update of your model
        }

    }
于 2012-06-25T12:53:52.793 回答