最近在做一个Java Swing的应用程序,使用到了JTable控件,需求就是当我点击Enter按键的时候,table能够换列,原先没有思路,然后再问答里提问了,有位小伙伴跟我说了用ActoinMap,非常感谢,现在问题解决了,和大家分享下,源码如下
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
public class JTableResponseEnterKey extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
public JTableResponseEnterKey() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 705, 502);
setVisible(true);
}
public void init() {
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
table = new JTable();
table.setModel(new DefaultTableModel(new Object[][] {
{ "一", "二", "三" }, { "四", "五", "六" }, }, new String[] { "第一列", "第一列", "第一列" }));
ActionMap am = (ActionMap) UIManager.get("Table.actionMap");
am.put("selectNextRowCell", new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
if(table.getEditingColumn() == -1){ //假如当前没有选中编辑列,默认第一行第一列
table.editCellAt(0, 0);
}else if (table.getEditingColumn() < table.getColumnCount() - 1) {
System.out.println("focus下一列");
table.editCellAt(table.getEditingRow(),table.getEditingColumn() + 1);
} else {
System.out.println("focus下一行");
table.editCellAt(table.getEditingRow() + 1, 0);
}
}
});
table.setActionMap(am);
contentPane.add(table, BorderLayout.CENTER);
}
public static void main(String[] args) {
new JTableResponseEnterKey();
}
}