概要

TabComponentを使用するJTabbedPaneで、タブ名称を編集更新します。

サンプルコード

class TabTitleRenamePopupMenu extends JPopupMenu {
  private final JTextField textField = new JTextField(10);
  private final Action renameAction = new AbstractAction("rename") {
    @Override public void actionPerformed(ActionEvent e) {
      JTabbedPane t = (JTabbedPane) getInvoker();
      int idx = t.getSelectedIndex();
      String title = t.getTitleAt(idx);
      textField.setText(title);
      int result = JOptionPane.showConfirmDialog(t, textField, "Rename",
          JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
      if (result == JOptionPane.OK_OPTION) {
        String str = textField.getText();
        if (!str.trim().isEmpty()) {
          t.setTitleAt(idx, str);
          JComponent c = (JComponent) t.getTabComponentAt(idx);
          c.revalidate();
        }
      }
    }
  };
  private final Action newTabAction = new AbstractAction("new tab") {
    @Override public void actionPerformed(ActionEvent evt) {
      JTabbedPane t = (JTabbedPane) getInvoker();
      int count = t.getTabCount();
      String title = "Tab " + count;
      t.add(title, new JLabel(title));
      t.setTabComponentAt(count, new ButtonTabComponent(t));
    }
  };
  private final Action closeAllAction = new AbstractAction("close all") {
    @Override public void actionPerformed(ActionEvent evt) {
      JTabbedPane t = (JTabbedPane) getInvoker();
      t.removeAll();
    }
  };

  public TabTitleRenamePopupMenu() {
    super();
    textField.addAncestorListener(new AncestorListener() {
      @Override public void ancestorAdded(AncestorEvent e) {
        textField.requestFocusInWindow();
      }

      @Override public void ancestorMoved(AncestorEvent e) {}

      @Override public void ancestorRemoved(AncestorEvent e) {}
    });
    add(renameAction);
    addSeparator();
    add(newTabAction);
    add(closeAllAction);
  }

  @Override public void show(Component c, int x, int y) {
    JTabbedPane t = (JTabbedPane) c;
    renameAction.setEnabled(t.indexAtLocation(x, y) >= 0);
    super.show(c, x, y);
  }
};
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、タブを閉じるJButtonTabComponentに追加したJTabbedPaneにタブ名称を変更するJPopupMenuを設定しています。

参考リンク

コメント