当按下Enter键时,如何确定选择JTable的哪个部分?

时间:2011-03-17 15:23:09

标签: java swing jtable key-bindings keylistener

我有JTable。我想知道当用户按 Enter 时选择了哪一行和哪一行。我怎样才能获得这些信息?

3 个答案:

答案 0 :(得分:1)

I TableModelListener。 tableChanged()方法中的TableModelEvent将告诉您哪些行和列是更改的来源。

答案 1 :(得分:1)

所有Swing组件都使用Actions来处理击键。 Enter键的默认操作是将单元格选择向下移动一行。如果要更改此行为,则需要使用自定义操作替换默认操作。

查看Key Bindings以获取有关如何替换操作的简单说明。

答案 2 :(得分:-1)

将此添加到您的表格中。 introwClicked有两个colClicked全局变量。应该好转


        table.addMouseListener(new MouseAdapter(){
            public void mouseReleased(MouseEvent e)
            {
                rowClicked = rowAtPoint(e.getPoint());
                colClicked = columnAtPoint(e.getPoint());
            }

            public void mouseClicked(MouseEvent e)
            {
                rowClicked = rowAtPoint(e.getPoint());
                colClicked = columnAtPoint(e.getPoint());
            }
        });

如果您在谈论使用键盘注册活动,则必须找到所选的单元格,然后向其添加KeyListener。您可以使用以下代码查找所选单元格。请注意,它实际上取决于单元格选择模式。


public void getSelectedCells()
    {
        if (getColumnSelectionAllowed() && ! getRowSelectionAllowed())
        {
            // Column selection is enabled
            // Get the indices of the selected columns
            int[] vColIndices = getSelectedColumns();
        }
        else if (!getColumnSelectionAllowed() && getRowSelectionAllowed())
        {
            // Row selection is enabled
            // Get the indices of the selected rows
            int[] rowIndices = getSelectedRows();
        }
        else if (getCellSelectionEnabled())
        {
            // Individual cell selection is enabled

            // In SINGLE_SELECTION mode, the selected cell can be retrieved using
            setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            int rowIndex = getSelectedRow();
            int colIndex = getSelectedColumn();

            // In the other modes, the set of selected cells can be retrieved using
            setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

            // Get the min and max ranges of selected cells
            int rowIndexStart = getSelectedRow();
            int rowIndexEnd = getSelectionModel().getMaxSelectionIndex();
            int colIndexStart = getSelectedColumn();
            int colIndexEnd = getColumnModel().getSelectionModel().getMaxSelectionIndex();

            // Check each cell in the range
            for (int r = rowIndexStart; r < = rowIndexEnd; r++)
            {
                for (int c = colIndexStart; c < = colIndexEnd; c++)
                {
                    if (isCellSelected(r, c))
                    {
                        // cell is selected
                    }
                }
            }
        }
    }