我有以下要求: 1.在JTable中按下tab / enter键时,读取所选单元格中的值并转到下一个单元格 2.无论单元格处于选择模式还是编辑模式,都应该发生这种情况
当按下F2键编辑具有现有值的单元格并按下回车键时,写入的程序不起作用。对于所有其他情况,它工作正常。
更新:要重新创建此问题,请按以下步骤操作:
输入单元格(0,0) - >按回车键 - >使用左箭头转到单元格(0,0) - >按F2键 - >在单元格(0,0)中输入b - >按enter键 - >此处执行的操作不会被调用。
请查看以下计划,并告诉我为满足要求所做的更改。
TableTest.java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TableTest extends JFrame
{
private JTable table;
private JScrollPane scrollPane;
public TableTest()
{
setSize( 400, 400 );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable( 10, 4 );
table.setRowSelectionAllowed( false );
table.setColumnSelectionAllowed( false );
table.setCellSelectionEnabled( false );
scrollPane = new JScrollPane( table );
String solve = "Solve";
KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(tab, solve);
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(enter, solve);
table.getActionMap().put(solve, new EnterAction());
add( scrollPane, BorderLayout.CENTER );
}
public static void main(String[] args)
{
TableTest tt = new TableTest();
tt.setVisible( true );
}
}
EnterAction.java:
import javax.swing.*;
import java.awt.event.*;
public class EnterAction extends AbstractAction
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("actionPerformed");
JTable tab = (JTable) e.getSource();
if (tab.isEditing())
tab.getCellEditor().stopCellEditing();
int row = tab.getSelectedRow();
int col = tab.getSelectedColumn();
System.out.println("1." + row + " " + col + " " + tab.getValueAt(row,col));
tab.changeSelection(row,col+1,false, false);
}
}