我正在为我的列(ButtonColumns)使用 TableCellEditor,如下所示。 当我输入向下键时,与 Jtable 关联的按键事件未触发。请指导我解决这个障碍,提前谢谢。下面的SSCCE如下
class ButtonEditor_Utility extends DefaultCellEditor {
protected JButton button;
public ButtonEditor_Utility() {
button.setActionCommand(tableName);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(table.getSelectionBackground());
} else {
button.setForeground(table.getForeground());
button.setBackground(table.getBackground());
}
label = (value == null) ? "" : value.toString();
button.setText(label);
isPushed = true;
return button;
}
public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
Class Test extent JFframe{
public void AddButtonColumn(){
tblDetailInfo.getColumn(1).setCellEditor(
new ButtonEditor_Utility(new JCheckBox(), this, 1, selectedRow, this,null, "TestDB"));}
//下面的事件没有响应向下键 //其 key 代码是40
private void tblDetailInfoKeyPressed(java.awt.event.KeyEvent evt){
// TODO add your handling code here:
if (evt.getKeyCode() == 40) {
int rowId = tblDetailInfo.getRowCount() - 1;
setSelectedRow(rowId);
tblDetailInfo.setCellSelectionEnabled(true);
tblDetailInfo.changeSelection(rowId, 0, false, false);
tblDetailInfo.requestFocus();
tblDetailInfo.scrollRectToVisible(new Rectangle(tblDetailInfo.getCellRect(rowId, 0, true)));
AddDetailRow();
}
}
private void formWindowOpened(java.awt.event.WindowEvent evt){ AddButtonColumn(); }
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Test test = new Test();
test.setVisible(true);
}
});
} }
}
最佳答案
不要尝试强制使用 JLabel
和 KeyEvent
作为表格单元格编辑器,而是使用实际的 TableCellEditor
,例如 @camickr 的 ButtonColumn
。这个TableTest
说明了一种使用 ButtonColumn
的方法在 JTable
中。优点是您可以获得所有熟悉的key bindings用于导航(箭头键)和激活(空格键)。
关于java - JTable 按键事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11412307/