Posted by terai at 2010-01-18
JFrameのタイトルバーなどの装飾を独自のものにカスタマイズする
JFrameのタイトルバーなどを非表示にして独自に描画し、これに移動リサイズなどの機能も追加します。
サンプルコード
class ResizeWindowListener extends MouseAdapter {
private Rectangle startSide = null;
private final JFrame frame;
public ResizeWindowListener(JFrame frame) {
this.frame = frame;
}
public void mousePressed(MouseEvent e) {
startSide = frame.getBounds();
}
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);
}
}
解説
上記のサンプルではタイトルバーを、setUndecorated(true)で非表示にし、移動可能にしたJPanelを追加してタイトルバーにしています。 リサイズは、Swing - Undecorated and resizable dialogやBasicInternalFrameUI.javaなどを参考にして、周辺にそれぞれ対応するリサイズカーソルを設定したJLabelを配置しています。
JDK 1.7.0 の場合、JFrameの背景色を透明(frame.setBackground(new Color(0,0,0,0)))にし、ContentPaneの左右上の角をクリアして透明にしています。