KeyStroke cStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK);
inputMap.put(cStroke, "none");
I已尝试在单元格本身中添加CTRL C:在表格本身中添加键盘列器。它不起作用。以及以下代码:
Action actionListener = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("activated");
}
};
KeyStroke cStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK);
inputMap.put(cStroke, actionListener);
它没有激活。
我读了
jtable:覆盖ctrl+c行为
,但它不包含答案,至少没有特定的答案。
CTRL+C将所选内容副本副本副本副本副本。您可以更改选择模式并选择单个单元格,CTRL+C仅复制此单元格。这可能是更自然的方式。下面的类显示一个具有切换选择模式的按钮的表。但是我不太确定如何从不同列中选择两个单元格。
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
public class TableSelectionModeExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable Selection Mode Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sample data for the table
Object[][] data = {
{"1", "John", "Doe"},
{"2", "Jane", "Smith"},
{"3", "Alice", "Johnson"}
};
String[] columns = {"ID", "First Name", "Last Name"};
DefaultTableModel model = new DefaultTableModel(data, columns);
JTable table = new JTable(model);
// Create a button to cycle through selection modes
JButton selectionModeButton = new JButton("Row Selection"); // Initial button text
selectionModeButton.addActionListener(e -> cycleSelectionMode(table, selectionModeButton));
// Add components to the frame
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.add(selectionModeButton, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
private static void cycleSelectionMode(JTable table, JButton button) {
// Determine the current selection mode and cycle to the next one
if (table.getRowSelectionAllowed() && !table.getColumnSelectionAllowed()) {
// Current mode: Row selection -> Switch to cell selection
table.setRowSelectionAllowed(false);
table.setColumnSelectionAllowed(false);
table.setCellSelectionEnabled(true);
button.setText("Cell Selection"); // Update button text
} else if (table.getCellSelectionEnabled()) {
// Current mode: Cell selection -> Switch to column selection
table.setCellSelectionEnabled(false);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
button.setText("Column Selection"); // Update button text
} else if (table.getColumnSelectionAllowed()) {
// Current mode: Column selection -> Switch back to row selection
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
button.setText("Row Selection"); // Update button text
}
}
}