如何使 JTable 单元格不可编辑但应该能够选择和复制当前单元格中的值
Posted
技术标签:
【中文标题】如何使 JTable 单元格不可编辑但应该能够选择和复制当前单元格中的值【英文标题】:how to make JTable cell non editable but should be able to select and copy the value in current cell 【发布时间】:2020-05-22 00:14:31 【问题描述】:我正在尝试使 JTable 单元格不可编辑,但如果我这样做,当我尝试复制整行时,我无法选择单个单元格值 我只想复制选定的单元格值而不是整行。有什么办法吗?
public class EmployeeWin extends JFrame
DefaultTableModel model = new DefaultTableModel()
@Override
public boolean isCellEditable(int row, int column)
return false;
;
Container cont = this.getContentPane();
JTable tab = new JTable(model);
private TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(model);
private final JTextField searchFilter = new JTextField();
public EmpDataWin(List<EmployeeDTO> pEmployeeDTO)
initialize(pEmployeeDTO);
public void initialize(List<EmployeeDTO> pEmployeeDTOList)
JPanel panelParent = new JPanel(new BorderLayout());
// Add Header
model.addColumn("Employee Name");
model.addColumn("Department");
model.addColumn("Details");
// Add data row to table
for (EmployeeDTO aEmployeeDTO : pEmployeeDTOList)
model.addRow(new Object[] aEmployeeDTO.getEmployee_Name(), aEmployeeDTO.getDepartment(),
aEmployeeDTO.getDetails());
tab.setRowSorter(rowSorter);
tab.setAutoCreateRowSorter(true);
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel(UIConstants.SEARCH), BorderLayout.WEST);
JTextField searchFilter = SearchFilter.createRowFilter(tab);
panel.add(searchFilter, BorderLayout.CENTER);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
tab.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane sp = new JScrollPane(tab,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
panelParent.add(panel,BorderLayout.NORTH);
panelParent.add(sp,BorderLayout.CENTER);
panelParent.setBorder(BorderFactory.createEmptyBorder(10 , 10, 10, 10));
cont.add(panelParent);
this.pack();
public static void main(String[] args)
EmployeeDAO dao = new EmployeeDAO();
List<EmployeeDTO> dto = dao.getemployeeData();
JFrame frame = new EmployeeDataWin(dto);
【问题讨论】:
【参考方案1】:当我尝试复制整行被选中时,我只想复制选定的单元格值而不是整行
Ctrl+C
键的默认 Action
是复制整行。如果您只想要当前选定单元格的数据,则需要将默认的Action
替换为自定义的Action
。
逻辑是这样的:
Action copyCell = new AbstractAction()
@Override
public void actionPerformed(ActionEvent e)
JTable table = (JTable)e.getSource();
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
Object value = table.getValueAt(row, column);
// copy the data to the clipboard
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection testData = new StringSelection( value.toString() );
c.setContents(testData, testData);
;
table.getActionMap().put("copy", copyCell);
以上代码将创建自定义Action
,并将其替换为JTable
的ActionMap
。见Key Bindings。链接中提供的程序显示了所有默认操作和每个操作的关键字。
【讨论】:
添加一个JPopupMenu
(使用相同的Action
),你就有了很好的解决方案以上是关于如何使 JTable 单元格不可编辑但应该能够选择和复制当前单元格中的值的主要内容,如果未能解决你的问题,请参考以下文章