Swing/LayoutAnimation のバックアップの現在との差分(No.3)
TITLE:LayoutManagerを使ってパネルの展開アニメーションを行う
Posted by terai at 2010-11-22
LayoutManagerを使ってパネルの展開アニメーションを行う
パネルの展開・収納をアニメーションで行うLayoutManagerを作成します。- category: swing folder: LayoutAnimation title: LayoutManagerを使ってパネルの展開アニメーションを行う tags: [LayoutManager, Animation, BorderLayout, JTree, JPanel] author: aterai pubdate: 2010-11-22T14:41:14+09:00 description: パネルの展開・収納をアニメーションで行うLayoutManagerを作成します。 image:
概要
パネルの展開・収納をアニメーションで行うLayoutManager
を作成します。
- &jnlp;
- &jar;
- &zip;
Screenshot
Advertisement
サンプルコード
#spanend
#spandel
private javax.swing.Timer animator = null;
#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
#spanadd
private Timer animator;
#spanend
private boolean isHidden = true;
private final JPanel controls = new JPanel(new BorderLayout(5, 5) {
private int controlsHeight = 0;
private int controlsPreferredHeight = 0;
private int controlsHeight;
private int controlsPreferredHeight;
@Override public Dimension preferredLayoutSize(Container target) {
// synchronized (target.getTreeLock()) {
Dimension ps = super.preferredLayoutSize(target);
controlsPreferredHeight = ps.height;
if(animator!=null) {
if(isHidden) {
if(controls.getHeight()<controlsPreferredHeight) controlsHeight += 5;
}else{
if(controls.getHeight()>0) controlsHeight -= 5;
if (animator != null) {
if (isHidden) {
if (controls.getHeight() < controlsPreferredHeight) {
controlsHeight += 5;
}
} else {
if (controls.getHeight() > 0) {
controlsHeight -= 5;
}
}
if(controlsHeight<=0) {
if (controlsHeight <= 0) {
controlsHeight = 0;
animator.stop();
}else if(controlsHeight>=controlsPreferredHeight) {
} else if (controlsHeight >= controlsPreferredHeight) {
controlsHeight = controlsPreferredHeight;
animator.stop();
}
}
ps.height = controlsHeight;
return ps;
}
});
#spanadd
#spanend
private Action makeShowHideAction() {
return new AbstractAction("Show/Hide Search Box") {
@Override public void actionPerformed(ActionEvent e) {
if(animator!=null && animator.isRunning()) return;
isHidden = controls.getHeight()==0;
animator = new javax.swing.Timer(5, new ActionListener() {
if (animator != null && animator.isRunning()) {
return;
}
isHidden = controls.getHeight() == 0;
animator = new Timer(5, new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
controls.revalidate();
}
});
animator.start();
}
};
}
解説
上記のサンプルでは、LayoutManager#preferredLayoutSize(...)をオーバーライドして、パネルの高さを更新するアニメーションを行っています。解説
-
Timer
を使用して5ms
ごとに子パネルの高さを更新 -
LayoutManager#preferredLayoutSize(...)
メソッドをオーバーライドして子パネルの高さの変更を展開アニメーションとして表現 - 内部の
JTree
の高さを縮小せずに重ねる状態で検索パネルを表示する場合はBorderLayout
ではなくOverlayLayout
をJTextAreaをキャプションとして画像上にスライドインのように使用する方法がある
参考リンク
参考リンク
- JTreeのノードを検索する
-
JTree
のノードを検索するサンプル
-
- JTextAreaをキャプションとして画像上にスライドイン