我有一个JTable
,我想通过在单元格中单击鼠标右键来打开PopupMenu。我通过制作自己的AbstractCellEditor
进行了尝试,但是没有用(当我启动程序时,当第一个方法初始化CellEditor
时(这是该方法做的最后一件事),CellEditor
是但是在下一个方法的开头,CellEditor
已经消失了。有人能帮帮我吗?我试图查找错误已有数周之久。
这是CellEditor
的代码:
public class CellEditor extends AbstractCellEditor implements TableCellEditor {
JTextField component;
JPopupMenu popmen;
CellEditor(){
component = new JTextField();
popmen = new JPopupMenu();
createPopmen(component);
component.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e) {
if ( e.isPopupTrigger() )
popmen.show( e.getComponent(), e.getX(), e.getY() );
}
});
}
public Component getTableCellEditorComponent1(JTable table, Object value,
boolean isSelected, int rowIndex, int vColIndex) {
if (isSelected) {
}
component.setText((String)value);
return component;
}
public Object getCellEditorValue() {
return component.getText();
}
@Override
public Component getTableCellEditorComponent(JTable arg0, Object arg1, boolean arg2,int arg3, int arg4) {
return null;
}
public void createPopmen(final JTextField text){
// creating Popmen
}
}
这是代码的一部分,我的表正在发生什么:
Vector<Vector> nu = new Vector<Vector>();
Vector<String> columnNames = new Vector<String>();
TableModel model;
model = new DefaultTableModel(nu, columnNames){
public Class getColumnClass() {
Class returnValue;
if ((3 >= 0) && (3 < getColumnCount())) {
System.out.println(getValueAt(0, 3));
returnValue = getValueAt(0, 3).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
}
public boolean isCellEditable(int row, int col) {
if(col == 0){
return false;
}
else{
return true;
}
}
};
table = new JTable(model);
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
int a = table.getSelectedRow();
if (!changes.contains(a) && a!=-1 && table.getSelectedColumn() != 0){
changes.add(a);
saved = false;
}
}
});
// SearchingBar
textfield.addKeyListener( new KeyListener(){
@Override
public void keyPressed(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent arg0) {
String searchedText =textfield.getText();
if (searchedText.length() == 0) {
sorter.setRowFilter(null);
} else {
sorter.setRowFilter(RowFilter.regexFilter(searchedText));
}
}
@Override
public void keyTyped(KeyEvent arg0) {
}
});
((DefaultTableModel) model).removeRow(0);
table.setModel(model);
table.setCellEditor(new CellEditor());
最佳答案
无需创建自定义编辑器。您应该能够执行以下操作:
JTable table = new JTable(...);
DefaultCellEditor dce = table.getDefaultEditor(Object.class);
Component editor = dce.getComponent();
editor.addMouseListener(...);
另外,请阅读Swing教程中关于Sorting and Filtering的部分,以获取有关如何使用过滤的有效示例。您不应该使用KeyListener。
如果您需要更多帮助,请发布您的SSCCE来演示问题。