我努力让JTable的单元格通过弹出菜单直接进入编辑模式(通过右键单击一个单元格显示)。我发现的任何信息都说明了如何更改所需的点击次数,而不是选择JMenu项目。
希望这段代码有助于理解我想要实现的目标:
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
public class CellTest{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
p.add(new CustomTable());
f.add(p);
f.pack();
f.setVisible(true);
}
}
class CustomTable extends JTable implements ActionListener{
JPopupMenu popup;
JMenuItem unlock;
public CustomTable(){
setModel(new CustomTableModel());
popup = new JPopupMenu();
unlock = new JMenuItem("Unlock");
unlock.addActionListener(this);
popup.add(unlock);
addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e){maybeShowPopup(e);}
@Override
public void mouseReleased(MouseEvent e){maybeShowPopup(e);}
});
}
private void maybeShowPopup(MouseEvent e){
int row = getSelectedRow();
if(row >= 0 && row < getRowCount())
setRowSelectionInterval(row,row);
else
clearSelection();
if(row < 0) return;
if(e.isPopupTrigger() && e.getComponent() instanceof JTable){
popup.show(e.getComponent(),e.getX(),e.getY());
}
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Code to put the cell into edit mode?");
}
}
class CustomTableModel extends AbstractTableModel{
String[][] data = {{"Nick","25","Swindon"},{"Will","47","Coventry"}, {"Jane","28","Reading"}};
@Override
public int getRowCount(){
return data[0].length;
}
@Override
public int getColumnCount(){
return 3;
}
@Override
public Object getValueAt(int row, int col){
return data[row][col];
}
@Override
public boolean isCellEditable(int row, int col){
return true;
}
}