TITLE:JFrameのタイトルバーなどの装飾を独自のものにカスタマイズする

Posted by at 2010-01-18

JFrameのタイトルバーなどの装飾を独自のものにカスタマイズする

`JFrame`のタイトルバーなどを非表示にして独自に描画し、これに移動リサイズなどの機能も追加します。

  • &jnlp;
  • &jar;
  • &zip;
CustomDecoratedFrame.png

サンプルコード

class ResizeWindowListener extends MouseAdapter {
  private Rectangle startSide = null;
  private final JFrame frame;
  public ResizeWindowListener(JFrame frame) {
    this.frame = frame;
  }
  @Override public void mousePressed(MouseEvent e) {
    startSide = frame.getBounds();
  }
  @Override public void mouseDragged(MouseEvent e) {
    if(startSide==null) return;
    Component c = e.getComponent();
    if(c==topleft) {
      startSide.y += e.getY();
      startSide.height -= e.getY();
      startSide.x += e.getX();
      startSide.width -= e.getX();
    }else if(c==top) {
      startSide.y += e.getY();
      startSide.height -= e.getY();
    }else if(c==topright) {
      startSide.y += e.getY();
      startSide.height -= e.getY();
      startSide.width += e.getX();
    }else if(c==left) {
      startSide.x += e.getX();
      startSide.width -= e.getX();
    }else if(c==right) {
      startSide.width += e.getX();
    }else if(c==bottomleft) {
      startSide.height += e.getY();
      startSide.x += e.getX();
      startSide.width -= e.getX();
    }else if(c==bottom) {
      startSide.height += e.getY();
    }else if(c==bottomright) {
      startSide.height += e.getY();
      startSide.width += e.getX();
    }
    frame.setBounds(startSide);
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルではタイトルバーを、`setUndecorated(true)で非表示にし、移動可能にしたJPanel`を追加してタイトルバーにしています。 リサイズは、Undecorated and resizable dialog | Oracle Forumsや`BasicInternalFrameUI.javaMetalRootPaneUI#MouseInputHandlerなどを参考にして、周辺にそれぞれ対応するリサイズカーソルを設定したJLabel`を配置しています。


`JDK 1.7.0の場合、JFrameの背景色を透明(frame.setBackground(new Color(0,0,0,0));)にし、ContentPane`の左右上の角をクリアして透明にしています。

参考リンク

コメント

  • `bloggerの方にコメントをもらって、調査、修正中だけど、dual-monitor`環境が無いのでテストしづらい…。 -- aterai
  • blogspotで指摘されていた件について: このサンプルを`1.6.0_xx+WebStartで実行すると、画面の外にフレームをドラッグすることが出来なかったのですが、JREのバージョンを1.7.0にすると、WebStart`で起動しても画面外に移動可能になっているみたいです。もしかしてデュアルディスプレイでも移動できるようになっているのかも?(確認してないですが...) -- aterai
  • マルチモニター関係のメモ: Bug ID: 7123767 Wrong tooltip location in Multi-Monitor configurations -- aterai