我想要做的是当用户完成表格单元格中的数据编辑,根据用户输入的内容将焦点移动到另一个单元格,并将该单元格转换为编辑模式,以便用户可以立即开始键入而无需其他操作.这样,用户可以专注于他的工作,软件将"思考"下一个应该编辑哪个单元格.
在现实生活中看起来不那么简单的简单任务......有人有点想法吗?
请试试这个例子.
它应该让你通过输入上,下,左,右的值u,d,l,r来浏览表格.
希望这能让你了解如何做到这一点.
import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class Test extends JFrame { private JTable table; private TableModel tableModel; public Test() { tableModel = new DefaultTableModel(5, 5); table = new JTable(tableModel); table.setColumnSelectionAllowed(true); getContentPane().add(table); Action handleEnter = new AbstractAction() { public void actionPerformed(ActionEvent e) { table.getCellEditor().stopCellEditing(); // store user input int row = table.getSelectedRow(); int col = table.getSelectedColumn(); String val = String.valueOf(table.getValueAt(row, col)).toLowerCase(); if (val.equals("u")) --row; else if (val.equals("d")) ++row; else if (val.equals("l")) --col; else if (val.equals("r")) ++col; if ( row >= 0 && row < tableModel.getRowCount() && col >= 0 && col < tableModel.getColumnCount()) { table.changeSelection(row, col, false, false); table.editCellAt(row, col); } } }; // replace action for ENTER, since next row would be selected automatically table.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "handleEnter"); table.getActionMap().put("handleEnter", handleEnter); } public static void main(String[] args) { Test test = new Test(); test.setSize(800, 600); test.setVisible(true); } }