#navi(contents-page-name): No such page: ST
FrontPage>Swing Tips>ST/TabbedPane

ST/TabbedPane

2024-01-27 (土) 14:37:42
  • category: swing folder: TabbedPane title: JTabbedPaneでタブを追加削除 tags: [JTabbedPane, JPopupMenu] author: aterai pubdate: 2003-12-22 description: ポップアップメニューを使って、JTabbedPaneにタブを追加、削除します。 image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTULwZD83I/AAAAAAAAAlo/NwNuK8prCFY/s800/TabbedPane.png

概要

ポップアップメニューを使って、JTabbedPaneにタブを追加、削除します。 JTabbedPane

#ref(): File not found: "TabbedPane.png" at page "Swing/TabbedPane"

サンプルコード

#spanend
#spanadd
JPopupMenu popup = new JPopupMenu() {
#spanend
  @Override public void show(Component c, int x, int y) {
    // JDK 1.3:
    // closePageAction.setEnabled(
    //     tabs.getUI().tabForCoordinate(tabs, x, y) >= 0);
    closePageAction.setEnabled(tabs.indexAtLocation(x, y) >= 0);
    closeAllAction.setEnabled(tabs.getTabCount() > 0);
    closeAllButActiveAction.setEnabled(tabs.getTabCount() > 0);
    super.show(c, x, y);
  }
#spanadd
};
#spanend
#spanadd
View in GitHub: Java, Kotlin
private void showTabPop(MouseEvent e){
  JPopupMenu pop = new JPopupMenu();
  AbstractAction action = new NewTabAction(MENUITEM_NEWTAB, null);
  pop.add(action);
  pop.addSeparator();
  action = new ClosePageAction(MENUITEM_CLOSEPAGE, null);
  boolean flg = false;
  for(int i=0;i<tab.getTabCount();i++){
    if(tab.getBoundsAt(i).contains(e.getPoint())){
      flg = true;
      break;
    }
  }
  action.setEnabled(flg);
  pop.add(action);
  pop.addSeparator();
  action = new CloseAllAction(MENUITEM_CLOSEALL, null);
  pop.add(action);
  action = new CloseAllButActiveAction(MENUITEM_CLOSEALLBUTACTIVE, null);
  pop.add(action);
  pop.show(tab, e.getX(), e.getY());
}

解説

上記のサンプルではJPopupMenuからJTabbedPaneにタブの追加、削除などが実行可能です。
  • 削除メニューは、タブタイトル上で右クリックされた場合のみ選択可
    • タブタイトル上でマウスがクリックされたかどうかは、JDK 1.4で導入されたJTabbedPane#indexAtLocation(...)メソッドで判定(タブ以外の場所がクリックされた場合は-1が返される)

参考リンク

JTabbedPane#indexAtLocation(int, int) (Java Platform SE 8)

コメント