所述
row从得到的
columnAtPoint()是在 图 坐标,而
removeRow()假定 模型
坐标。引用相关教程部分:
除非通过排序,过滤或用户对列的 *** 作重新排列了查看的数据,否则区别并不重要。
如果是这样,您将需要使用
convertRowIndexToModel()在
排序和过滤
末尾介绍的,它建议:
使用分类器时,请始终记住要转换单元格坐标。
另外,请考虑使用
ListSelectionListener代替
MouseAdapter。
附录:您的实现
getValueAt()继续访问提供给构造函数的数组,而模型的数据实际上存储在父实现中。如果你真的需要在模型的数据结构的更多控制,扩展
AbstractTableModel
import java.awt.EventQueue;import java.awt.Point;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.Jframe;import javax.swing.JScrollPane;import javax.swing.JTable;import javax.swing.table.DefaultTableModel;public class MainJF extends Jframe { private JTable tagsJT; private TagsSelectionTableModel model; private static int COLUMN_CHECK = 0; private static int COLUMN_TAG_NAME = 1; private static int COLUMN_TAG_ID = 2; private static int COLUMN_EDIT_TAG = 3; private static int COLUMN_DELETE_TAG = 4; public MainJF() { this.add(new JScrollPane(createTagsTable())); pack(); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private JTable createTagsTable() { String[] columnNames = {"0", "Tag", "2", "3", "4"}; Object[][] data = new Object[10][columnNames.length]; for (int i = 0; i < data.length; i++) { data[i][COLUMN_CHECK] = false; data[i][COLUMN_TAG_NAME] = "Tag " + i; data[i][COLUMN_TAG_ID] = i; data[i][COLUMN_EDIT_TAG] = "edit"; data[i][COLUMN_DELETE_TAG] = "delete"; } model = new TagsSelectionTableModel(columnNames, data); tagsJT = new JTable(model); tagsJT.setRowSelectionAllowed(true); tagsJT.addMouseListener(new TagsTableMA()); return tagsJT; } class TagsSelectionTableModel extends DefaultTableModel { public TagsSelectionTableModel(String[] columnNames, Object[][] data) { super(data, columnNames); } } class TagsTableMA extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { Point p = e.getPoint(); int row = tagsJT.rowAtPoint(p); int col = tagsJT.columnAtPoint(p); if (col == COLUMN_DELETE_TAG) { model.removeRow(row); } } } public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainJF().setVisible(true); } }); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)