Java 按下Enter键时,如何确定选择了JTable的哪一部分?
我有一个Java 按下Enter键时,如何确定选择了JTable的哪一部分?,java,swing,jtable,key-bindings,keylistener,Java,Swing,Jtable,Key Bindings,Keylistener,我有一个JTable。我想知道当用户按Enter键时选择了哪一行和哪一列。如何获取此信息?将此信息添加到您的表中。有两个int全局变量用于rowClicked和colClicked。应该可以走了 table.addMouseListener(new MouseAdapter(){ public void mouseReleased(MouseEvent e) { rowClicked = rowAt
JTable
。我想知道当用户按Enter键时选择了哪一行和哪一列。如何获取此信息?将此信息添加到您的表中。有两个int
全局变量用于rowClicked
和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
}
}
}
}
}
实施。from The tableChanged()方法将告诉您更改的来源是哪一行和哪一列。所有Swing组件都使用动作来处理按键笔划。Enter键的默认操作是将单元格选择向下移动一行。如果要更改此行为,则需要将默认操作替换为自定义操作
查看有关如何替换操作的简单说明。@User,KeyListener不会捕获单元格上的事件。2*-1表示侦听器,+1表示收集选定单元格