如何清除JTable中选定单元格的内容?
How to clear contents of selected cells in JTable?
我用鼠标在一些JTable
单元格中拖出选区,选区是黄色的,谁能告诉我如何按"Delete"清除选中单元格的内容在键盘或 JButton
?
中键入
所选单元格的截图:
创建一个 Acton
以查找选定的单元格并清除文本。最简单的方法是遍历 table.
中的每个单元格
Action
的基础是这样的:
Action clearAction = new Action()
{
@Override
public void actionPerformed(ActionEvent e)
{
for (each row in the table)
for (each column in the row)
if (table.isCellSelected(...))
table.setValueAt("", ...);
}
}
然后创建一个按钮来调用操作:
JButton clearButton = new JButton( "Clear" );
clearButton.addActionListener( clearAction );
如果您还想使用 Delete 键,则可以使用 Key Bindings
共享相同的操作。
向 JTable 添加新键绑定的基本逻辑是:
String keyStrokeAndKey = "DELETE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, keyStrokeAndKey);
table.getActionMap().put(keyStrokeAndKey, action);
查看 Key Bindings 了解更多信息。
我用鼠标在一些JTable
单元格中拖出选区,选区是黄色的,谁能告诉我如何按"Delete"清除选中单元格的内容在键盘或 JButton
?
所选单元格的截图:
创建一个 Acton
以查找选定的单元格并清除文本。最简单的方法是遍历 table.
Action
的基础是这样的:
Action clearAction = new Action()
{
@Override
public void actionPerformed(ActionEvent e)
{
for (each row in the table)
for (each column in the row)
if (table.isCellSelected(...))
table.setValueAt("", ...);
}
}
然后创建一个按钮来调用操作:
JButton clearButton = new JButton( "Clear" );
clearButton.addActionListener( clearAction );
如果您还想使用 Delete 键,则可以使用 Key Bindings
共享相同的操作。
向 JTable 添加新键绑定的基本逻辑是:
String keyStrokeAndKey = "DELETE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, keyStrokeAndKey);
table.getActionMap().put(keyStrokeAndKey, action);
查看 Key Bindings 了解更多信息。