TITLE:JTableのセルエディタにJPopumMenuを設定

Posted by terai at 2010-04-26

JTableのセルエディタにJPopumMenuを設定

JTableのセルエディタに、Copy,Paste,Undo,Redoなどを行うJPopumMenuを設定します。

  • &jnlp;
  • &jar;
  • &zip;

#screenshot

サンプルコード

class TextFieldPopupMenu extends JPopupMenu {
  private final UndoManager manager = new UndoManager();
  private final Action undoAction   = new UndoAction(manager);
  private final Action redoAction   = new RedoAction(manager);
  private final Action cutAction    = new DefaultEditorKit.CutAction();
  private final Action copyAction   = new DefaultEditorKit.CopyAction();
  private final Action pasteAction  = new DefaultEditorKit.PasteAction();
  private final Action deleteAction = new AbstractAction("delete") {
    public void actionPerformed(ActionEvent e) {
      ((JTextComponent)getInvoker()).replaceSelection(null);
    }
  };
  public TextFieldPopupMenu(final JTextComponent tc) {
    super();
    tc.addAncestorListener(new AncestorListener() {
      public void ancestorAdded(AncestorEvent e) {
        manager.discardAllEdits();
        tc.requestFocusInWindow();
      }
      public void ancestorMoved(AncestorEvent e) {}
      public void ancestorRemoved(AncestorEvent e) {}
    });
    tc.getDocument().addUndoableEditListener(manager);
    tc.getActionMap().put("undo", undoAction);
    tc.getActionMap().put("redo", redoAction);
    InputMap imap = tc.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK), "undo");
    imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK), "redo");

    add(cutAction);
    add(copyAction);
    add(pasteAction);
    add(deleteAction);
    addSeparator();
    add(undoAction);
    add(redoAction);
  }
  public void show(Component c, int x, int y) {
    JTextField field = (JTextField)c;
    boolean flg = field.getSelectedText()!=null;
    cutAction.setEnabled(flg);
    copyAction.setEnabled(flg);
    deleteAction.setEnabled(flg);
    undoAction.setEnabled(manager.canUndo());
    redoAction.setEnabled(manager.canRedo());
    super.show(c, x, y);
  }
}

解説

上記のサンプルでは、JTableのセルエディタに、Cut,Copy,Paste,Delete,Undo,Redoを行うJPopumMenuを設定しています。セルエディタのJTextFieldは使いまわしているので、AncestorListenerを使って表示されるたびに、UndoManager#discardAllEdits()を呼び出して、UndoManagerを空にしています。

コメント